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

checkbox - Why is my click event called twice in jquery?

Why is my click event fired twice in jquery?

HTML

<ul class=submenu>
    <li><label for=toggle><input id=toggle type=checkbox checked>Show</label></li>
</ul>

Javascript

$("ul.submenu li:contains('Show')").on("click", function(e) {
    console.log("toggle");
    if ($(this).find("[type=checkbox]").is(":checked")) console.log("Show");
    else console.log("Hide");
});

This is what I get in console:

toggle                     menu.js:39
Show                       menu.js:40
toggle                     menu.js:39
Hide                       menu.js:41


> $("ul.submenu li:contains('Show')")
[<li>?                                            ]
    <label for=?"toggle">?
      <input id=?"toggle" type=?"checkbox" checked>?
      "Show"
    </label>?
</li>?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If I remember correctly, I've seen this behavior on at least some browsers, where clicking the label both triggers a click on the label and on the input.

So if you ignore the events where e.target.tagName is "LABEL", you'll just get the one event. At least, that's what I get in my tests:


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

...