【问题标题】:jquery conditional operator for attr function用于 attr 函数的 jquery 条件运算符
【发布时间】:2013-03-23 06:23:49
【问题描述】:
$("<button>")
    .addClass("radio")
    .addClass(this._getValue(lbl) ? "checked" : "")
    .attr(this._getDisableProp(lbl) ? ("disabled", "disabled") : "")
    .prop(this._getDisableProp(lbl) ? ("disabled", true) : ("disabled", false));

在上面的代码中,我试图添加 attrprop 仅当我的函数返回 true 时。我对addClass 做了同样的事情,它有效,但它不适用于attrprop

请问有什么解决办法吗?

【问题讨论】:

    标签: jquery ternary-operator


    【解决方案1】:

    您不能根据三元运算符选择多个函数参数。您只能选择一个。所以做类似的事情:

    $("button")
             .addClass("radio")
             .addClass(this._getValue(lbl) ? "checked" : "")
             .attr("disabled" , this._getDisableProp(lbl) ? "disabled" : "")
             .prop("disabled", this._getDisableProp(lbl) ? true : false);
    

    但是我建议只使用属性,因为设置为“”的“禁用”属性仍然会禁用元素(无论如何都会被属性覆盖):

    $("button")
             .addClass("radio")
             .addClass(this._getValue(lbl) ? "checked" : "")
             .prop("disabled", this._getDisableProp(lbl) ? true : false);
    

    【讨论】:

    • api.jquery.com/prop(属性与属性).. 读到这说明了为什么我同时使用 attr 和 prop
    【解决方案2】:

    做这样的事情:

    .prop("disabled", this._getDisableProp(lbl))
    

    您不希望对整个事物使用三元运算符...只是值(根据条件会有所不同)

    请注意,即使 disabled 属性为空值也会导致元素被禁用,这就是我们使用 prop 的原因。

    【讨论】:

      【解决方案3】:

      你不能直接那样做,但你可以这样做:

      var btn = document.createElement("button");
      btn.className = "radio";
      if( this._getValue(lbl)) btn.className += " checked";
      if( this.getDisableProp(lbl)) btn.disabled = true;
      

      有时在多个步骤中使用纯 JavaScript 比尝试一次性链接所有内容更容易;)

      【讨论】:

        【解决方案4】:

        按照你的风格,

          $("<button>")
                .addClass("radio")
                .addClass(this._getValue(lbl) ? "checked" : "") 
                .prop('disabled',this._getDisableProp(lbl));
        

        更灵活的方法,

        $("<button>")
            .addClass("radio")
            .addClass(function () {
                if(this._getValue(lbl)) return 'disabled';
             }) 
            .prop('disabled',function () {
                return this._getDisableProp(lbl) ;
             });
        

        另外,你为什么同时使用attrprop 来添加disabled 属性。您应该只使用 propdisabled 不需要值。

        【讨论】:

        • api.jquery.com/prop(属性与属性).. 读到这说明了为什么我同时使用 attr 和 prop
        • 我已经多次阅读该链接。它总是令人困惑。你能澄清一下吗?
        猜你喜欢
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 2017-01-15
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多