Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

html - Retrieve boolean data from data attribute in jquery

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

If you want to get the raw data (without the automatic data conversion), you can use .attr():

$('#test').attr("data-return");

See the working test case here: http://jsfiddle.net/jfriend00/6BA8t/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...