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
199 views
in Technique[技术] by (71.8m points)

JQuery readOnly strange behavior

I have the following HTML code:

<input type="text" id="test" ><br>
<button onclick="makeReadOnly('true')">Make read only (ok)</button>
<button onclick="makeReadOnly('false')">Make read/write (not ok)</button> 
<button onclick="makeReadOnly(false)">Make read/write (ok)</button>

with this script:

function makeReadOnly(r) {
    $("#test").prop("readOnly", r);

}

My problem is: call to makeReadOnly(false) works, while makeReadOnly('false') doesn't.

But makeReadOnly('true') works.

(tested with JQuery 1.9.1)

Who can explain me why ?

http://jsfiddle.net/ym9qe99p/1/

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because of casting. The string "false" is cast as a Boolean true. Basically, any non-empty string is (along with 0 and a couple other things). Try it! Boolean("false").

The readOnly property casts its input to a Boolean. Therefore both "true" and "false" become true, and only false stays false.


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

...