问题描述
如何基于与某些变量匹配的选项将已选择"属性添加到下拉菜单选项中?
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>');
}
我想根据一个选项的值是否与另一个变量匹配来将其标记为选中".因此,如果loginOption[i]
等于var existingLoginValue
,则将该选项设置为'selected'
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'
可以做到的
if(loginOptions[i] === existingLoginValue){ print 'selected'; };
谢谢!
推荐答案
我会使用 .val()
在方法的最后,它基于值进行设置,如下所示:
I'd use .val()
at the end of your method, this sets based on value, like this:
$('#Login').val(existingLoginValue);
类似地,要获取该值,请在不使用诸如此类的任何参数的情况下调用它:
Similarly, to get the value, call it without any parameters like this:
var currentValue = $('#Login').val();
这篇关于添加“选定的"归因于jQuery的下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!