【问题标题】:Why $().prop() will not set attribute value?为什么 $().prop() 不会设置属性值?
【发布时间】:2014-05-27 12:09:04
【问题描述】:

为什么.prop不会在例子中设置属性值?使用 Bootstrap 3.1.1 和 jQuery 2.1。

HTML

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="checkbox"> Option 1
    </label>
    <label class="btn btn-primary">
        <input type="checkbox"> Option 2
    </label>
    <label class="btn btn-primary">
        <input type="checkbox"> Option 3
    </label>
</div>

jQuery

$('label').click
(
    function()
    {
        // Does not set attribute
        $(this).prop('foo','bar');
    }
);

Live demo

【问题讨论】:

  • 代码必须进入问题。您的问题不能依赖 3rd 方链接来得到有意义的回答。
  • 我将链接中的代码添加到问题中,但不确定编辑是否意味着这样做
  • 这到底是怎么回事?
  • 您正在尝试禁用标签,而不是输入元素。使用 .find() 获取输入元素。关闭此问题的原因是它不包含任何代码,只是指向您网站的链接。
  • @عثمانغني 我已经投票决定重新提出这个问题。

标签: javascript jquery twitter-bootstrap button twitter-bootstrap-3


【解决方案1】:

您需要使用attr() 而不是prop() 之类的,

$('label').click(function(){
    // Use attr as disabled is not a property of a label
    $(this).attr('disabled',true);
});

disabled 不是标签的属性,因此正如您尝试的那样,它不适用于label。 如果要添加disabled 作为属性,则需要使用attr()

Live Demo

【讨论】:

  • OP 已经说过他的目的是为元素添加一个属性。他只是以禁用为例
【解决方案2】:

labels 没有内置的 disable 属性。您需要添加一个类来自己禁用它们。

类似:

.disabled {
   background-color: #428bca;
}

并将类添加到您的元素:

$(this).addClass('disabled');

【讨论】:

    【解决方案3】:

    您好,您对 attr 和 prop 感到困惑, 在很多情况下两者都不同,link 将解决您的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多