我知道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">
。
尝试使用 .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
(布尔值)已更改为复选框状态
HTML属性始终是字符串值。如果你确实想要设置字符串以外的东西,那么请考虑使用jQuery.data()
尝试使用 .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
(布尔值)已更改为复选框状态
HTML属性始终是字符串值。如果你确实想要设置字符串以外的东西,那么请考虑使用jQuery.data()