在jquery中从数据属性中检索布尔数据 [英] Retrieve boolean data from data attribute in jquery
问题描述
我正在尝试从html DIV元素中检索Boolean类型的数据属性,但是当字符串转换为boolean时,它总是返回false。
I am trying to retrieve a data attribute of type Boolean from an html DIV element , however it is always returning false when the string is converted to boolean .
HTML
<div id='test' data-return="true"></div>
JS
isreturn_str = $('#test').data('return');
isreturn = (isreturn_str === 'true');
if (isreturn) {
document.write("It is true");
} else {
document.write("It is false");
}
输出
output
这是假的
It is false
http://jsfiddle.net/neilghosh/494wC/
推荐答案
jQuery .data()
方法很聪明,可以识别布尔值和数值,并将它们转换为原生类型。所以这返回布尔值 true
,而不是true
:
The jQuery .data()
method is smart about recognizing boolean and numeric values and converts them into their native type. So this returns the boolean true
, not "true"
:
$('#test').data('return');
如果您想要获取原始数据(没有自动数据转换),您可以使用 .attr()
:
If you want to get the raw data (without the automatic data conversion), you can use .attr()
:
$('#test').attr("data-return");
请参阅这里的工作测试用例: http://jsfiddle.net/jfriend00/6BA8t/
See the working test case here: http://jsfiddle.net/jfriend00/6BA8t/
这篇关于在jquery中从数据属性中检索布尔数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!