2012-05-30 3 views
0

동적으로 의존하는 4 개의 선택 메뉴가 있습니다. 메뉴는 주, 카운티, 지역, 이웃에 해당합니다. 동적 종속성은 jQuery 스크립트를 통해 달성됩니다. 내가 성취하고자하는 것은 각 메뉴에 대해 사용자가 선택한 마지막 옵션을 메뉴에 기억시키는 것입니다. 그래서 트릭을 수행 할 URL 매개 변수를 가져올 수 있다고 생각했습니다. 그래서 나는jquery로 선택 메뉴 옵션 기억하기

getCounty: function (results) { 
    if(!results) return; 
    var allCounties = $("<option value=\"All\">All Counties </option>"); 
    counties.html(results); 
    counties.prepend(allCounties); 
    var w = $.query.get("county_id"); 
    if(w) { 
     counties.val(w).attr('selected', true); 
    } else { 
     counties.val("All").attr('selected', true); 
    } 

$.query.get 기능 정확 .... 이런 식으로 스크립트를 수정? 내 코드에 문제가 있습니까? 나는 내가 jQuery를 전문가가 아니라고 인정해야 ... 코드는 내가

counties.val(3).attr('selected',true) 

선택 메뉴의 세 번째 옵션이 선택됩니다를 입력하면 잘 작동합니다.

내가,

var county = getUrlVars()["county_id"]; 

    if (county)  
    counties.val(county).attr('selected',true); 
    else 
     counties.val("All").attr('selected',true); 
+0

왜'attr ('selected', true)'를 사용합니까? – zerkms

답변

1

I는 "county_id"무엇을 잘 모릅니다,하지만 난 supose 대한 기타 메뉴 후

function getUrlVars() { 
    var vars = {}; 
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { 
    vars[key] = value; 
    }); 
    return vars; 
} 

그리고를 사용하여 문제를 해결 어쩌면 더 나은 :

getCounty: function (results) { 
if(!results) return; 
var allCounties = $("<option value=\"All\">All Counties </option>"); 
counties.html(results); 
counties.append(allCounties); ///The all option first 
var w = $('#county_id :selected').val(); ///w is the value of option selected of other combo 
counties.find('option[value='+w+']').attr('selected', 'selected'); ///this find a option with value W, if exist mark like selected 
} 
+1

나는 .get 함수를 사용했기 때문에 url 매개 변수 (사용자가 무언가를 마지막으로 검색했을 때 실행 된 쿼리)에 대해 이야기하고 있다는 것을 알았을 것이라고 생각했습니다. 어쨌든 나는 url 매개 변수를 가져오고 문제를 해결 한 전통적인 자바 스크립트 함수를 발견했다. 시간을내어 대충 대답 해 주셔서 대단히 감사합니다. 답변을 통해 내 jquery 지식을 풍부하게했습니다! – user926652