Javascript: Clicking a wrapper element but not a child element

I am writing some javascript (jQuery) that enables a div wrapped around a checkbox, when clicked, will toggle the checkbox element. However, the problem I'm running into is that when you click on the checkbox, it doesn't work because it's being toggled twice (at least I think that's what's happening). [Here's a demo.][1] Here's the code: $('.checkbox-wrapper').click(function(){ var $checkbox = $(this).find('input[type="checkbox"]'); if ($checkbox.is(':checked')) { $checkbox.attr('checked', false); } else { $checkbox.attr('checked', true); } }); How can I make it so that clicking the checkbox works as normal, but if you click in the surrounding area, it toggles the checkbox? ##Solution: Thanks to jAndy's comment for showing how this can be done by checking the event.target property: $('.checkbox-wrapper').click(function(e){ if( e.target.nodeName === 'INPUT' ) { e.stopPropagation(); return; } var $checkbox = $(this).find('input[type="checkbox"]'); if ($checkbox.is(':checked')) { $checkbox.attr('checked', false); } else { $checkbox.attr('checked', true); } }); And as others have pointed out, this may not be the best example since you get the same functionality (without needing javascript) by wrapping the checkbox with a label tag instead of a div tag. [Demo][2] [1]: http://jsfiddle.net/misbehavens/WV7sp/ [2]: http://jsfiddle.net/misbehavens/cuhwE/

以上就是Javascript: Clicking a wrapper element but not a child element的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏