[英]Add the “selected” attribute to a drop down option with jQuery
How do I add the attribute "selected" to a drop down menu option based on that option matching some variable? 如何基于与某些变量匹配的选项将“选定”属性添加到下拉菜单选项?
Here is how the dropdown is populated... 这是下拉列表的填充方式...
loginOptions = ["First", "Second", "Third"];
var Login = $( '#Login' );
for ( var i = 0; i < loginOptions.length; i++ ) {
Login.append('<option value="'+ loginOptions[i] +'">'+ loginOptions[i] +'</option>');
}
I want to mark one option as "selected" based on whether or not its value matches another variable. 我想根据一个选项的值是否匹配另一个变量来将其标记为“选定”。 so if loginOption[i]
is equal to var existingLoginValue
then set that option to 'selected' 因此,如果loginOption[i]
等于var existingLoginValue
则将该选项设置为“ selected”
Something that would do 会做的事情
if(loginOptions[i] === existingLoginValue){ print 'selected'; };
Thanks! 谢谢!
If you only want to do one value then yeah, the val()
works. 如果只想做一个值,那么val()
可以了。 Otherwise, you can also do this: 否则,您也可以这样做:
$option=$('<option value="'+ loginOptions[i] +'">'+ loginOptions[i]+'</option>').appendTo(Login);
if (loginOptions[i] == existingLoginValue) {
$option.attr('selected',true)
}
er, someone pointed out this doesn't really make sense since that would imply multiple options with the same value. 嗯,有人指出这并没有什么意义,因为这意味着多个具有相同值的选项。 I meant to write something like this: 我打算写这样的东西:
existingLoginValues = ['foo','bar']
$option=$('<option value="'+ loginOptions[i] +'">'+ loginOptions[i]+'</option>').appendTo(Login);
if (existingLoginValues.indexOf(loginOptions[i]) != -1) {
$option.attr('selected',true)
}
the indexOf
function is supported in most browsers except (of course) IE6. 除了(当然)IE6,大多数浏览器都支持indexOf
函数。 See "Best way to find an item in a JavaScript Array?" 请参阅“在JavaScript数组中查找项目的最佳方法?”
采用
$('#Login').selectedIndex = i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.