Javascript 如果选择菜单中没有.contains(“something”)选项,请执行操作
如果Javascript 如果选择菜单中没有.contains(“something”)选项,请执行操作,javascript,jquery,Javascript,Jquery,如果.contains(“exampleValue”)查找未找到的选项,我正试图找出一种方法来设置myVariable=false 这就是我试过的 try { $('select').find('option:contains("exampleValue")').prop('selected', true); } catch(e) { console.log(e); myVariable = false; } 但是catch从不执行。catch
.contains(“exampleValue”)
查找未找到的选项,我正试图找出一种方法来设置myVariable=false
这就是我试过的
try {
$('select').find('option:contains("exampleValue")').prop('selected', true);
} catch(e) {
console.log(e);
myVariable = false;
}
但是
catch
从不执行。catch
不会执行,因为try
中没有任何内容会引发错误-您可以执行以下操作,而不是try/catch
:
var option = $('select').find('option:contains("exampleValue")');
if (option.length) {
option.prop("selected", true);
} else {
myVariable = false;
}
jQuery的find返回一个空集合。如果没有找到任何内容,它不会引发异常……您是否希望该行引发异常?因为这就是
try catch
catch