Javascript和JQuery,如何验证select中是否存在选项元素?

H.S*_*idl 8 jquery select

使用JQuery,我试图根据查询字符串在'select'元素中设置一个选项.

这个问题与类似,但是我仍然需要知道如何在执行选择之前检查元素是否存在,否则页面将自动刷新(请参阅下面的退出条件).

使用函数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();
}
Run Code Online (Sandbox Code Playgroud)

更新:有效的解决方案是:

    //Checks if the option exists, and returns otherwise
    if (!selectObject.find('option[value=' + valueToSelect + ']').length)
        return;
Run Code Online (Sandbox Code Playgroud)

Den*_*ovs 18

试着检查一下 selectObject.find('option[value="'+valueToSelect +'"]').length > 0

  • 将`valueToSelect`的值包装在引号中似乎更安全:`selectObject.find('option [value ="'+ valueToSelect +'"]').length()` (3认同)