使用jquery设置布尔属性 [英] Setting a boolean attribute with jquery
问题描述
据我所知,jquery允许您使用.attr()方法修改属性。基本上有两种方法:
I understand that jquery will allow you to modify attributes with the .attr() method. There are basically two methods:
$('#element').attr('attribute', 'value') // sets the attribute
var attribute = $('#element').attr('attribute') // gets the attribute
我的问题是,你如何设置一个布尔属性,例如复选框上的'checked'或select标签上的'multiple'?
My question is, how do you set a boolean attribute such as 'checked' on a checkbox or 'multiple' on a select tag?
我尝试过以下操作但没有成功:
I've tried doing the following without success:
$('#element').attr('attribute', true)
$('#element').attr('attribute', '')
所有这些都添加了属性,但通常喜欢这个< tag attribute =attribute>
。
All of these add the attribute but usually like this <tag attribute="attribute">
.
推荐答案
尝试使用 .prop
来处理支持属性的 boolean
选中/停用/已选中
等
Try using .prop
to deal with boolean
that is for supported attributes like selected/disabled/checked
e.t.c
$('#element').prop('attribute', true);
(例如)
elem.checked
返回 true
(布尔值)将随复选框状态而变化
elem.checked
returns true
(Boolean) Will change with checkbox state
$(elem).prop(checked)
返回 true
(布尔值)会改变with checkbox state
$(elem).prop("checked")
returns true
(Boolean) Will change with checkbox state
elem.getAttribute(checked)
返回checked
(String)复选框的初始状态;不会改变
elem.getAttribute("checked")
returns "checked"
(String) Initial state of the checkbox; does not change
$(elem).attr(checked)(1.6)
返回checked
(String)复选框的初始状态;不会改变
$(elem).attr("checked")(1.6)
returns "checked"
(String) Initial state of the checkbox; does not change
$(elem).attr(checked)(1.6.1 +)
返回checked
(String)将随复选框状态而变化
$(elem).attr("checked")(1.6.1+)
returns "checked"
(String) Will change with checkbox state
$(elem).attr (选中)(1.6之前)
返回 true
(布尔值)已更改为复选框状态
$(elem).attr("checked")(pre-1.6)
returns true
(Boolean) Changed with checkbox state
这篇关于使用jquery设置布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!