最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery Event Bubbling CheckBox - Stack Overflow

programmeradmin4浏览0评论

I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm trying to do (DON'T run the code as below as it creates an endless loop).

<script>
$(document).ready(function() {
  $("form p").click(function() {
    $(this).find("input").click();
  });

  $("form input").click(function() {
    alert("clicked");
  });  
});
</script>


<form>
<p> <input type="checkbox" name="checker" value="1" /> Click anywhere</p>
<p> <input type="checkbox" name="checker2" value="2" /> Click anywhere</p>
</form>

I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm trying to do (DON'T run the code as below as it creates an endless loop).

<script>
$(document).ready(function() {
  $("form p").click(function() {
    $(this).find("input").click();
  });

  $("form input").click(function() {
    alert("clicked");
  });  
});
</script>


<form>
<p> <input type="checkbox" name="checker" value="1" /> Click anywhere</p>
<p> <input type="checkbox" name="checker2" value="2" /> Click anywhere</p>
</form>
Share Improve this question asked Jan 18, 2009 at 22:46 Brian FisherBrian Fisher 24k15 gold badges80 silver badges82 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Use the LABEL tag: http://www.w3schools./tags/tag_label.asp

clicking on any <input> tag triggers the click event of <p> tag (because <input> tag is inside the <p> tag) which then triggers the click event of <input> tag leading to an endless loop.

You can prevent the 'endless loop' using jQuery's event.stopPropagation method.

发布评论

评论列表(0)

  1. 暂无评论