为什么$()。prop()不会设置属性值?

时间:2014-05-27 12:09:05

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

为什么.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

3 个答案:

答案 0 :(得分:2)

您需要使用attr()而不是prop()

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

已停用不属于标签的属性,因此您无法使用label,因为您已尝试过。 如果您想将disabled添加为属性,则需要使用attr()

Live Demo

答案 1 :(得分:0)

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

类似的东西:

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

并将该类添加到元素中:

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

答案 2 :(得分:0)

嗨,我在attr和prop之间感到困惑, 两者在许多情况下都不同,link将解决您的问题