根据jQuery 1.7中的文本检查是否存在选择选项 [英] Check if an select option exists based on text in jQuery 1.7

查看:75
本文介绍了根据jQuery 1.7中的文本检查是否存在选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下HTML:

So I have the following piece of 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>

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

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

推荐答案

请尝试以下操作:

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

演示

编辑:上面的代码片段使用jQuery 包含选择器,该选择器过滤其textContent 包含的元素指定的值。要获得完全匹配,您可以使用christian-mann的答案中建议的代码段。

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


如何使用Javascript(而不是jquery)执行此操作 - Jerry

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



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

这篇关于根据jQuery 1.7中的文本检查是否存在选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆