使用jquery设置布尔属性

时间:2012-10-17 18:17:55

标签: jquery

据我所知,jquery允许您使用.attr()方法修改属性。基本上有两种方法:

$('#element').attr('attribute', 'value') // sets the attribute
var attribute = $('#element').attr('attribute') // gets the attribute

我的问题是,如何设置一个布尔属性,例如复选框上的'checked'或select标签上的'multiple'?

我尝试过以下操作但没有成功:

$('#element').attr('attribute', true)
$('#element').attr('attribute', '')

所有这些都添加了属性,但通常都是这样的<tag attribute="attribute">

3 个答案:

答案 0 :(得分:17)

尝试使用.prop处理支持属性的boolean,例如selected/disabled/checked e.t.c

$('#element').prop('attribute', true);
来自jQuery docs,(一个例子)

elem.checked返回true(布尔值)将随复选框状态

而变化

$(elem).prop("checked")返回true(布尔值)将随复选框状态

而变化

elem.getAttribute("checked")返回"checked"(字符串)复选框的初始状态;不会改变

$(elem).attr("checked")(1.6)返回"checked"(字符串)复选框的初始状态;不会改变

$(elem).attr("checked")(1.6.1+)返回"checked"(字符串)将随复选框状态

而变化

$(elem).attr("checked")(pre-1.6)返回true(布尔值)已更改为复选框状态

答案 1 :(得分:0)

我在jQuery中使用此方法

<body>

或使用JavaScript:

jQuery('option').attr("selected", "");

只需要传递一个空字符串即可设置boolean属性。

答案 2 :(得分:-1)

HTML属性始终是字符串值。如果你确实想要设置字符串以外的东西,那么请考虑使用jQuery.data()

相关问题