使用JQuery,我試圖設置一個選項作爲選擇基於查詢字符串的'選擇'元素。Javascript和JQuery,如何驗證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 2012-03-14 08:39:44
我會更新示例如果可行,謝謝 – haschdl 2012-03-19 12:24:56