javascript 按文本查找选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11950434/
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
find select option by text
提问by CMR
Can anyone tell me why this works in older versions of jQuery (e.g. 1.4.2) but if you switch to a later version, e.g. (1.6 +) it stops working?
谁能告诉我为什么这在旧版本的 jQuery(例如 1.4.2)中有效,但是如果您切换到更高版本,例如(1.6 +)它停止工作?
http://jsfiddle.net/nmvf6/1194/
http://jsfiddle.net/nmvf6/1194/
$(function(){
$('#my_button').click(function(){
var unitName = "Unit2";
$('.assUnit').find('option[text="'+unitName+'"]').remove();
});
});
?
?
I have checked the error output in the console for the later versions, and an error seems to occur on the page load, before i've even got as far as it loading up my script and being able to click the button..
我已经检查了更高版本的控制台中的错误输出,页面加载时似乎发生了错误,在我什至加载我的脚本并能够单击按钮之前..
When I change the version to 1.8.0 for example and Run the page, this errorcomes up in my Opera scripts console:
例如,当我将版本更改为 1.8.0 并运行页面时,此错误出现在我的 Opera 脚本控制台中:
Which seems to be in a "mootools" file..but I didn't select mootools, i selected jQuery 1.8.0
这似乎在“mootools”文件中..但我没有选择 mootools,我选择了 jQuery 1.8.0
:/
:/
Thanks.
谢谢。
回答by undefined
You are using Attribute Equals
selector which selects elements that have the specified attribute with a value exactly equal to a certain value, option elements don't have text
attributes, you can use :contains
selector instead, try this:
您正在使用Attribute Equals
选择器,它选择具有与特定值完全相等的指定属性的元素,选项元素没有text
属性,您可以使用:contains
选择器代替,试试这个:
Select all elements that contain the specified text.
选择包含指定文本的所有元素。
$(function(){
$('#my_button').click(function(){
var unitName = "Unit2";
$('.assUnit').find('option:contains('+unitName+')').remove();
});
});
If you want to select the element that has only certain value you can use the filter
method:
如果要选择只有特定值的元素,可以使用以下filter
方法:
$(function(){
$('#my_button').click(function(){
var unitName = "Unit2";
$('.assUnit option').filter(function() {
return $(this).text() === unitName
}).remove();
});
});
回答by Ja?ck
You will probably have more luck with this:
你可能会有更多的运气:
$('.assUnit').find('option:contains('+unitName+')').remove();
See also: :contains() selector
回答by rajesh kakawat
try this
试试这个
$(function(){
$('#my_button').click(function(){
var unitName = "Unit2";
$(".assUnit option:contains('"+unitName+"')").remove();
});
});