attr('selected','selected') 在 jquery 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8339660/
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
attr('selected','selected') not work in jquery
提问by Shree
$('#sellist option').each(function(index) {
var str ='4/5/8';
var substr = str.split('/');
if (substr[0] == $(this).attr('value')) {
$(this).attr('selected','selected');
alert('hi'); ///For check
}
});
Every thing works fine and alertis fired. I havent any error in console. But #sellist optionis not selected which I want. What is my problem. Thanks.
一切正常并被alert解雇。我在控制台中没有任何错误。但#sellist option没有选择我想要的。我的问题是什么。谢谢。
回答by Brynner Ferreira
Replace attr by prop.
用 prop 替换 attr。
$('#element').prop('selected', true);
回答by Rory McCrossan
Your code is working fine. It is just selecting the first element of your array, 4because you are not looping through the array, you just use substr[0]to get the first value.
您的代码运行良好。它只是选择数组的第一个元素,4因为您没有遍历数组,您只是substr[0]用来获取第一个值。
To see that it works I changed the initial value to 7:
为了查看它是否有效,我将初始值更改为7:
$('#sellist option').each(function(index) {
var str = "7/5/8";
var substr = str.split('/');
if (substr[0] == $(this).val()) {
$(this).attr('selected', 'selected');
alert($(this).val()); ///For check
}
});
OP Clarified he want to loop around array
OP 澄清他想循环数组
To loop through your array and select each value in the multiple select, use this:
要循环遍历数组并选择多选中的每个值,请使用以下命令:
$('#sellist option').each(function(index) {
var str = "4/5/8";
var substr = str.split('/');
for (var i = 0; i < substr.length; i++) {
if (substr[i] == $(this).val()) {
$(this).attr('selected', 'selected');
}
}
});
回答by jabclab
$(this).attr('selected','selected');
should be replaced by:
应替换为:
$(this).attr('selected', true);
回答by xdazz
If you want one option to be selected, for example, you want the option with value 4to be selected, just do $('#sellist').val('4');
如果您希望选择一个选项,例如,您希望选择具有值的选项4,只需执行$('#sellist').val('4');
回答by Robin Castlin
$(this).attr('selected', true);should do the trick for ya.
$(this).attr('selected', true);应该为你做的伎俩。
回答by Akhil Thayyil
You can do like this
你可以这样做
$('#sellist').val($(this).attr('value'));
回答by Emre Erkan
You can make it like this:
你可以这样做:
var str ='4/5/8';
$.each(str.split('/'), function(i, val) {
$('#sellist option').filter('[value="' + val + '"]').prop('selected', 'selected');
});
Working example on jsFiddle
jsFiddle 上的工作示例

