javascript 根据 jQuery 1.7 中的文本检查选择选项是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11639023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:53:16  来源:igfitidea点击:

Check if an select option exists based on text in jQuery 1.7

javascriptjqueryhtmljquery-selectors

提问by yz10

So I have the following piece of HTML:

所以我有以下一段 HTML:

<select id="sel">
<option value="0">Option1</option>
<option value="1">Option2</option>
<option value="2">Option3</option>
<option value="3">Option4</option>
</select>

How do I check to see if #sel has an option based on the text value? ("Option1")

如何检查 #sel 是否有基于文本值的选项?(“选项1”)

回答by undefined

Try the following:

请尝试以下操作:

var opt = 'Option1';
if ($('#sel option:contains('+ opt +')').length) {
   alert('This option exists')
}

Demo

演示

edit: The above snippet uses the jQuery containsselector which filters elements that their textContent containsthe specified value. For an exact match you can use the code snippet suggested in christian-mann's answer.

编辑:上面的代码片段使用 jQuerycontains选择器来过滤它们的 textContent包含指定值的元素。对于完全匹配,您可以使用 christian-mann's answer 中建议的代码片段。

How to do this with Javascript (not jquery) – Jerry

如何使用 Javascript(不是 jquery)做到这一点——Jerry

var optionExists = [].some.call(document.getElementById('sel').options, function(option) {
   return option.textContent === 'value';
});

回答by Christian Mann

The jQuery filter function accepts a function as its argument:

jQuery 过滤器函数接受一个函数作为其参数:

$('#sel option').filter(function() { 
    return $(this).text() === "Option1"; 
});

回答by triplethreat77

var length = $('#sel option').filter(function() { 
    return $(this).text() === "Option1"; 
}).length;

if(length == 0)
    console.log('This option text doesn't exist.');
else
    console.log('This option text exists ' + length + ' times.');

If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.

如果长度为 0,则它不存在。我通常不喜欢使用 contains,因为它不是完全匹配的。

回答by adeneo

var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false