使用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