[英]jQuery for selecting options that have no value, or particular text
I have selects which all have a top option with text "All" and no value, but I need to write some code that works on all other options in these selects. 我选择了所有带有文本“ All”且没有值的顶部选项的选择,但是我需要编写一些适用于这些选择中所有其他选项的代码。
I have code as follow that works, but I'd rather do away with the conditional on the second line. 我有下面的代码可以正常工作,但是我宁愿取消第二行的条件。 I did try using jQuery's ':not' selector but couldn't figure out how to configure it for missing/null/undefined value. 我确实尝试使用jQuery的':not'选择器,但无法弄清楚如何为缺少/空/未定义的值配置它。 Would it best if I explicitly set value to the empty string "" and then use :not? 如果我将值显式设置为空字符串“”,然后使用:not,那将是最好的方法吗?
_.each($(select).find('option'), function(option) {
if (optionVal = $(option).val()) {
Please excuse my usage of _.each instead of jQuery's each, we'd rather stay consistent as we use underscore for lots more than just iterating over jQuery matched sets. 请原谅我对_.each而不是jQuery的用法,我们宁愿保持一致,因为我们使用下划线进行了很多操作,而不仅仅是遍历jQuery匹配集。
Off the top of my head, you could use either: 在我头顶上方,您可以使用以下任一方法:
$(select).find('option[value!=""]');
or 要么
$(select).find('option:not([value=""])');
to return the options that are not <option value="">All</option>
返回不是<option value="">All</option>
If the first option
is always the valueless option, you could also use: 如果第一个option
始终是无值选项,则还可以使用:
$(select).find('option:not(:eq(0))')
to select all option
elements that are not the first-child
. 选择不是第first-child
所有option
元素。
If you want to exclude the first Option from every Select element, you can use :not()
selector and .find()
method: 如果要从每个Select元素中排除第一个Option,可以使用:not()
选择器和.find()
方法:
$('select').find('option:not(:first)');
In case that you want to filter the Options that have value, you can use .filter()
method: 如果要过滤具有值的选项,可以使用.filter()
方法:
$('select option').filter(function() {
return $.trim(this.value).length;
});
Note for iterating through jQuery collections it's better to use jQuery's .each()
method, otherwise you will lose the chainabilty that jQuery provides. 请注意,要遍历jQuery集合,最好使用jQuery的.each()
方法,否则您将失去jQuery提供的可链接性。
$(select).find('option[value]'); // selects all <option>s with value
如果我没有正确理解这个问题。
You may try this 你可以试试这个
HTML: HTML:
<select>
<option>All</option>
<option value>0</option>
<option value=1>One</option>
<option value=2>Two</option>
</select>
JS: This will return only last two options (One and Two) JS:这只会返回最后两个选项(一个和两个)
$('select option').filter(function(){
return this.hasAttribute('value') && this.value.length;
});
to filter the options for missing/null/undefined
value. 筛选missing/null/undefined
值的选项。 Here is an example . 这是一个例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.