attr('selected','selected')在jquery中不起作用

Shr*_*ree 2 jquery

$('#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
    }
});
Run Code Online (Sandbox Code Playgroud)

每件事都很好,alert被解雇了.我在控制台中没有任何错误.但是#sellist option没有选择我想要的.我的问题是什么 谢谢.

Bry*_*ira 15

用prop替换attr.

$('#element').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

  • 这为我做到了。我想知道为什么,尤其是在多次更改所选选项后,.attr() 停止工作,但这有效 (2认同)