使用 jquery 更改选定的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11309817/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:27:52  来源:igfitidea点击:

Change selected index using jquery

jquery

提问by None

Hi need to change the selected index of a when another has been changed.. Example: i have

嗨,当另一个已更改时,需要更改 a 的选定索引。例如:我有

<select id="selector">
<option>No 1</option>
<option>No 2</option>
</select>
<select id="selected">
<option>ONE</option>
<option>TWO</option>
</select>

now i want the $selected index to change when the #selector's index is changed.. like when i change to "No 2" the other combobox will change to "TWO". pardon me for newbie question but im new to jquery ^^

现在我希望 $selected 索引在 #selector 的索引更改时更改..就像当我更改为“No 2”时,另一个组合框将更改为“TWO”。请原谅我的新手问题,但我是 jquery 的新手 ^^

回答by Sudhir Bastakoti

$('#selector').change(function() {
    var idx = this.selectedIndex;        
    $("select#selected").prop('selectedIndex', idx);  
});

回答by David says reinstate Monica

I'd suggest:

我建议:

$('#selector').change(
    function(){
        var index = this.selectedIndex;
        $('#selected option').eq(index).prop('selected',true);
    });

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by Anthony Grist

Just using regular JavaScript because jQuery seems unnecessary for this:

只使用常规的 JavaScript,因为 jQuery 似乎没有必要:

document.getElementById('selector').onchange = function() {
    document.getElementById('selected').selectedIndex = this.selectedIndex;
}

Working DEMO

工作演示

回答by diEcho

with jQuery 1.7.2

使用jQuery 1.7.2

$(document).on('change', '#selector', function (){
   var si =  this.selectedIndex
    $('#selected option').eq(si).prop('selected',true);
});?

Working DEMO

工作演示

回答by Naami

The selectedIndex starts at 0.

selectedIndex 从 0 开始。

If the drop-down list allows multiple selections it will only return the index of the first option selected.
The value "-1" will deselect all options (if any).
If no option is selected, the selectedIndex property will return -1.

如果下拉列表允许多选,它只会返回所选第一个选项的索引。
值“-1”将取消选择所有选项(如果有)。
如果未选择任何选项,则 selectedIndex 属性将返回 -1。

$('#idselect').change(function() {
    var index = this.selectedIndex;
    //...
});