问题 使用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">


1528
2017-10-17 18:17


起源



答案:


尝试使用 .prop 处理 boolean 这是支持的属性,如 selected/disabled/checked 等等

$('#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 (布尔值)已更改为复选框状态


17
2017-10-17 18:19





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


-1
2017-10-17 18:20



在HTML5中不正确: dev.w3.org/html5/spec/... - Chad Kapatch
你是对的,我不应该做出这样的假设......道歉 - ilan berci


答案:


尝试使用 .prop 处理 boolean 这是支持的属性,如 selected/disabled/checked 等等

$('#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 (布尔值)已更改为复选框状态


17
2017-10-17 18:19





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


-1
2017-10-17 18:20



在HTML5中不正确: dev.w3.org/html5/spec/... - Chad Kapatch
你是对的,我不应该做出这样的假设......道歉 - ilan berci