JQuery를 사용하여 쿼리 문자열을 기반으로 'select'요소에서 선택한대로 옵션을 설정하려고합니다.Javascript 및 JQuery, select에 select 요소가 있는지 확인하는 방법은 무엇입니까?
이 질문은 this과 비슷하지만 선택을 수행하기 전에 요소가 존재하는지 확인하는 방법을 알아야합니다. 그렇지 않으면 페이지가 계속 새로 고침됩니다 (아래 종료 조건 참조).
getParameterByName 함수를 사용하여 쿼리 문자열을 가져 오면 올바르게 작동합니다.
아래 현재의 구현 :
function setSelectedItem(selectName, itemToSelect) {
///<summary>Selects an HTML option element inside a HTML select element based on the value from the query string.</summary>
///<param name="selectName" type="string">The partial name of the HTML select in which 'itemToSelect' must be selected</param>
///<param name="itemToSelect" type="string">The name of the query string parameter which value is the of the 'option' element to select.</param>
//If an items has already been selected, return
if ($('select[name*=' + selectName + ']')[0].selectedIndex != 0) return;
//Fetches the value from the query string; if empty, returns
var valueToSelect = getParameterByName(itemToSelect);
if (valueToSelect == "") return;
//Fecthes the HTML select object
var selectObject = $('select[name*=' + selectName + ']');
//HERE how to check if 'valueToSelect' does not exist and return?
selectObject.val(valueToSelect).attr('selected', 'selected').change();
}
업데이트 : 일한 솔루션했다 :
//Checks if the option exists, and returns otherwise
if (!selectObject.find('option[value=' + valueToSelect + ']').length)
return;
값을 설정 성가신의 그러나 만약 당신이 계속해서 또 다시이 코드를 실행하는 경우는의 얻을 종류 그래서 나는 기능의 종류를 보장하는 작은 플러그인을 작성했습니다 '.val()'을 사용하면 그 항목을 선택할 것이므로'.attr ('selected', 'selected')'를 사용하는 이유는 무엇입니까? – nnnnnn
예제가 제대로 작동하면 업데이트 할 것입니다. – haschdl