【问题标题】:jQuery>=1.9: Selecting an option in a select tag is not "fully" selectedjQuery>=1.9:在选择标签中选择一个选项没有“完全”选择
【发布时间】:2013-09-14 03:14:07
【问题描述】:

在 jQuery >= 1.9 中有非常奇怪的行为!不知道是不是bug!

基本的 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 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! (Demo)

如果我们注释掉 $('#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”。那么这是一个错误吗?还是我做错了什么?

【问题讨论】:

  • 只需使用val方法$('#mySelect').val(3);
  • .prop() vs .attr()的可能重复
  • @undefined in jQuery>=1.9, $('#mySelect').val(3); 正确设置了值,但没有给选项 3 “selected”属性!
  • 请检查链接的问题,属性和属性之间有区别,DOM是基于属性的,属性在页面加载时映射到其对应的属性,selected是一个布尔属性。

标签: jquery select option html-select


【解决方案1】:

我认为你在混合 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/

【讨论】:

  • 不错的答案,但是如果您尝试在演示的最后一行添加alert($('#opt3').attr('selected'));,它会提示“未定义”,您没有在选项标签中添加“选择”属性!跨度>
  • $('#opt3').prop('selected', 'selected').attr('selected', 'selected');我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多