点击事件被触发两次 - jquery
我有以下简化的 html:
<div class="foo" style="width:200px; height:200px;">
<input type="checkbox" />
</div>
<script type="text/javascript">
$('.foo').click(function(){$(this).find('input:checkbox')[0].click();});
</script>
单击 200x200 div 'foo' 效果很好,并引发其中复选框的单击事件。
然而,当我准确地单击复选框本身时,它会触发其“正常”事件,加上上面的 jquery 绑定事件,这意味着复选框会检查自身,然后再次取消选中自身。
有没有一种简洁的方法来防止这种情况发生?
I have the following simplified html:
<div class="foo" style="width:200px; height:200px;">
<input type="checkbox" />
</div>
<script type="text/javascript">
$('.foo').click(function(){$(this).find('input:checkbox')[0].click();});
</script>
Clicking the 200x200 div 'foo' works well, and raises the click event for the checkbox inside it.
However when I exactly click the checkbox itself, it fires its 'normal' event, plus the jquery bound event above, meaning the checkbox checks itself, then unchecks itself again.
Is there a tidy way to prevent this from happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
怎么样:不使用 div,而是使用
。它在语义上更正确,完全符合您的要求,并且不需要 JavaScript。
此处的工作示例: http://jsfiddle.net/LhSG9/1/
How about this: instead of using a div, use a
<label>
. It's more semantically correct, does exactly what you want, and requires no JavaScript.Working example here: http://jsfiddle.net/LhSG9/1/
事件泡沫。您需要测试单击的
e.target
。如果您只是想选中/取消选中该框,则应该设置其
checked
属性。编辑:修正了一些错误。
工作演示: http://jsfiddle.net/LhSG9/
Events bubble. You would need test the
e.target
that was clicked.And if you're just trying to check/uncheck the box, you should set its
checked
property.EDIT: Fixed a couple mistakes.
Working demo: http://jsfiddle.net/LhSG9/
您需要停止单击复选框,这样它就不会冒泡到 div 中。
You need to stop the click on the checkbox so it does not bubble up to the div.
发生这种情况是因为当您单击复选框时,您也单击了 div,因为复选框位于其中。所以你应该做的是当用户点击 div 内部但没有点击复选框时捕获。如果用户单击该复选框,它将以其默认行为选中/取消选中
It happens because when you click on the checkbox you are also clicking on the div because the checkbox is inside it. So what you should do is capture when the user clicks the inside the div but no the checkbox. If the user does click on the checkbox it will act with its default behavior checking/unchecking
在 yiur
$(document).ready function
中包含以下函数 -为您的复选框提供一个 id say test - 然后 -
include the following function in yiur
$(document).ready function
-give an id say test to your checkbox then -