$('#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
}
});一切正常,alert被解雇了。我在控制台中没有任何错误。但是没有选择我想要的#sellist option。我的问题是什么。谢谢。
发布于 2011-12-01 18:25:56
您的代码运行良好。它只是选择数组的第一个元素4,因为您没有遍历数组,您只需要使用substr[0]来获取第一个值。
要查看它是否正常工作,我将初始值更改为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澄清了他希望在数组中循环
要遍历数组并选择多个select中的每个值,请使用以下命令:
$('#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');
}
}
});发布于 2014-03-09 10:13:18
用prop替换attr。
$('#element').prop('selected', true);发布于 2011-12-01 18:25:07
$(this).attr('selected','selected');应替换为:
$(this).attr('selected', true);https://stackoverflow.com/questions/8339660
复制相似问题