1

jQuery >= 1.9 中确实有奇怪的行为!我不确定这是否是一个错误!

基本的 HTML:

<select id="mySelect">
    <option value="1" id="opt1">Option 1</option>
    <option value="2" id="opt2">Option 2</option>
    <option value="3" id="opt3">Option 3</option>
    <option value="4" id="opt4">Option 4</option>
</select>

在 jQuery <= 1.8.3 中,以下代码完美运行(Demo):

<script>
    $(document).ready(function() {
        $('#opt3').attr('selected', 'selected');// this line..
        $('#mySelect').val($('#opt3').val());   // OR this line, OR both lines, alerts will always be the same:
        alert($('#opt3').attr('selected'));     // alert "selected"
        alert($('#mySelect').val());            // alert "3"
    });
</script>

而在 jQuery >= 1.9.0 中,第一个警报是“选择”,第二个警报是“1”而不是“3”,选项 1 选择不是选项 3!(演示

如果我们注释掉该行$('#opt3').attr('selected', 'selected');,下拉列表正确选择了选项 3,但alert($('#opt3').attr('selected'));警告“未定义”,选项 3 没有获得“选定”属性!代码应如下所示:

<script>
    $(document).ready(function() {
        //$('#opt3').attr('selected', 'selected');
        $('#mySelect').val($('#opt3').val());
        alert($('#opt3').attr('selected'));  // alert "undefined", no "selected" attribute set !!
        alert($('#mySelect').val());         // alert "3" correctly
    });
</script>

如果我们注释掉该行$('#mySelect').val($('#opt3').val());alert($('#opt3').attr('selected'));警报“选择”正确,但选择的值没有改变,警报“1”!代码应如下所示:

<script>
    $(document).ready(function() {
        $('#opt3').attr('selected', 'selected');
        //$('#mySelect').val($('#opt3').val());
        alert($('#opt3').attr('selected'));  // alert "selected" correctly
        alert($('#mySelect').val());         // alert "1" !!
    });
</script>

附言

顺便说一句,我知道有些人可能会建议$('#opt3').prop('selected', true);,但这没有任何效果。我想要实现的是为选项 3 提供“selected”属性,并将 select 的值设置为“3”。那么这是一个错误吗?还是我做错了什么?

4

1 回答 1

2

我认为您正在混合 prop 和 attr

你可以做:

$('#opt3').prop('selected', 'selected').attr('selected', 'selected');
$('#mySelect').attr('value',$('#mySelect').find(':selected').val());

alert($('#opt3').prop('selected'));
alert($('#mySelect').val());
alert($('#opt3').attr('selected'));

http://jsfiddle.net/AvpLw/

于 2013-09-10T12:22:55.907 回答