【问题标题】:set the selectedIndex of a DropDown using jQuery?使用 jQuery 设置 DropDown 的 selectedIndex?
【发布时间】:2012-05-09 01:40:07
【问题描述】:

我正在尝试将下拉列表的索引设置为 0;如果用户取消选中示例中所示的复选框,但有些人只是忽略了......

$ddlHeader.attr('selectedIndex', 0);

http://jsfiddle.net/abuhamzah/9YM4P/

//html:

Header:
<br /><input id="check" type="checkbox" name="approve" />
<select id="myddl" name="myddl">
    <option value="0">select me</option>
    <option value="1">One</option>
    <option value="2">Twooo</option>
    <option value="3">Three</option>
</select> 

//js

var $ddls = $('select');
var $check = $('#check');
var $ddlHeader = $("#myddl"); 

$ddls.prop("disabled", true); 

$check .click(function() {
    $ddls.prop("disabled", true); 
    $ddlHeader.prop("disabled", !this.checked);
    $ddlHeader.attr('selectedIndex', 0);

});

【问题讨论】:

    标签: jquery


    【解决方案1】:
    $ddlHeader.find('option:first').prop('selected', 'selected');
    

    Updated Fiddle

    更新:

    $('select').prop('selectedIndex', 0);
    

    或者使用更多代码但更灵活:

    $('select').each(function() {
        $(this).find('option:first').prop('selected', 'selected');
    });
    

    【讨论】:

    • 只是想理解你的代码......如果;如果我想要所有(find('select') 下拉列表被选择为 index = 0 你会怎么做?
    • 我有以下内容并且我不断收到null:stackoverflow.com/questions/29653375/…
    【解决方案2】:

    使用.prop,如下所示,

    $ddlHeader.prop('selectedIndex', 0);
    

    Updated fiddle

    【讨论】:

      【解决方案3】:

      UPD

      我混淆了selectedIndex 和价值。因此,仅当您明确希望选择 value = 0 时,此解决方案才有效:

      改用val(0)

      $check.click(function() {
          $ddls.prop("disabled", true); 
          $ddlHeader.prop("disabled", !this.checked);
          $ddlHeader.val(0);
      });
      

      http://jsfiddle.net/9YM4P/1/

      【讨论】:

      • @zerkms 不,您将值设置为 0 并且工作正常,因为相应的选项在索引 0 中
      • 它不会改变索引!它选择具有0 值的选项。 check this fiddle
      • @Vega:是的,我把它弄糊涂了-+1 为您的解决方案
      【解决方案4】:

      //这行代码对我有用。 $(function(){$("select").each(function (i) { $(this).prop("selectedIndex", 0); }); });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-20
        • 1970-01-01
        • 1970-01-01
        • 2011-07-19
        • 2017-09-11
        • 2012-06-25
        • 2017-07-18
        • 1970-01-01
        相关资源
        最近更新 更多