[英]javascript/jquery how to set more than one attributes
I have this for loop which will append options to that "optlist"; 我有这个for循环,它将在“ optlist”后面附加选项; the value will be set to manSel[i][0] and the text to manSel[i][1];
该值将设置为manSel [i] [0],文本设置为manSel [i] [1]; I would also like to set the attribute selected="selected" to all of them.
我还想将所有属性设置为selected =“ selected”。 Can I do that in the same loop or should I iterate again throug the options and add that attribute to each one of them.
我可以在同一循环中执行此操作吗?还是应该再次遍历选项并将该属性添加到每个选项中。 Thanks in advance!
提前致谢!
for(var i = 0 ; i<manSel.length; i++){
optlist.append($('<option/>').attr('value', manSel[i][0]).text(manSel[i][1]));
}
Try this: 尝试这个:
for(var i = 0 ; i<manSel.length; i++){
optlist.append($('<option/>').attr({value: manSel[i][0], selected: "selected"}).text(manSel[i][1]));
}
你可以用这个
optlist.append($('<option selected="selected"/>').attr('value', manSel[i][0]).text(manSel[i][1]));
To add more attributes use an object, this is very well explained in the jQuery Docs, I mean this is pretty basic stuff to find : 要使用对象添加更多属性,这在jQuery Docs中已得到很好的解释,我的意思是这是找到的相当基本的东西 :
$ele.attr({ href: '', src: '' })
In any case value
has a special method val()
: 在任何情况下,
value
都有一个特殊的val()
方法:
$ele.val(value)
And selected
is a property is meant to be used with prop()
. 并且
selected
是一个属性,该属性应与prop()
一起使用。
$ele.prop('selected', true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.