【问题标题】:Change properties of option in a select element with jQuery使用 jQuery 更改选择元素中的选项属性
【发布时间】:2013-11-12 19:45:06
【问题描述】:

代码:

function disableOption(pos)
{
    //document.getElementById("selectSuggestion").options[pos].disabled=true;   <-- this is what I want to do

    var option = $(#selectRating).children()[pos];              <-- doesnt work
    $(#selectRating).find(option).prop("disabled", true);

}

function addEventListeners()
{
    $(#selectRating).bind("focus", disableOption(0));
}

function init()
{
    addEventListeners();
}

$(document).ready(init);

我对 jQuery API 和语法不太熟悉,我检查了 http://api.jquery.com/category/traversing/ 和其他类似的线程,但没有找到解决方案。

编辑:

固定代码:

function disableOption(pos)
{
    $("#selectRating option:eq(" + pos + ")").prop("disabled", true);
}

function addEventListeners()
{
    $("#selectRating").on("focus", function() {disableOption(0);});
}

function init()
{
    addEventListeners();
}

$(document).ready(init);

【问题讨论】:

  • @Ryuji 您不需要在 disableoptions 中再次创建对象,请参阅我回答中的最后一个 sn-p。可以参考this
  • 请说明您对这个问题投反对票的理由。出现了一些错误(因为我没有检查选择器周围的引号),但除此之外,这个问题的问题和解决方案仍然相关。
  • @PSL 你能给我一个指向 .call() 函数文档的链接吗?我在 jQuery API 页面上找不到任何东西:api.jquery.com/?s=call
  • @Ryuji 并非如此,这完全取决于您的设计方式。这里只是因为您调用函数而不是绑定处理程序,请参阅我的答案中的解释。如果您知道它始终是第一选择,那么您就可以这样做。 function disableOption() { $(this).children(":eq(0)").prop("disabled", true); } $("#selectRating").bind("focus", disableOption);

标签: javascript jquery properties tree-traversal


【解决方案1】:

选择器周围的引号!

$("#selectRating")

也可以缩短:$(#selectRating).children()[pos];$("#selectRating option:eq(" + pos + ")").prop("disabled", true);

假设selectRatingselect 元素,如果不是,则忽略它。

【讨论】:

  • 我更喜欢“是你的选择器”,=p
【解决方案2】:

怎么样

$('#selectRating option:eq("' + pos + '")').prop('disabled', true);

【讨论】:

    【解决方案3】:

    您正在调用函数而不是将函数引用作为处理程序绑定到它,并记住选择器周围的引号。

    $(#selectRating).bind("focus", disableOption(0)); //This just invokes the function as you try to bind the handler.
    

    应该是

    $("#selectRating").bind("focus", function(){
         disableOption(0);
    });
    

    你只需要这样做:

    $("#selectRating").children(":eq(" + pos + ")").prop("disabled", true);
    

    或者简化为:

    function disableOption(pos) {
       $(this).children(":eq(" + pos + ")").prop("disabled", true);
    }
    
    function addEventListeners() {
        $('#selectRating').bind("focus", function(){
            disableOption.call(this, 0);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2011-01-30
      相关资源
      最近更新 更多