jQuery 单击事件处理程序为复选框调用两次 [英] jQuery click event handler is called twice for a checkbox
本文介绍了jQuery 单击事件处理程序为复选框调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 ASPX 页面中遇到以下代码问题:
I have a problem with the following code in an ASPX page:
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function() {
alert("click")
})
});
</script>
<asp:CheckBox runat="server" Text="Checkbox XYZ" CssClass="test" ID="cb1" />
在浏览器 (FF3.5/IE8) 中,我遇到以下问题:
In the browser (FF3.5 / IE8) I have the following problem:
- 如果我点击复选框(小方块),它会按预期工作
- 如果我单击复选框的文本(Checkbox XYZ"),则单击事件会触发两次,并且警报会显示两次.
我想这与复选框呈现为 HTML 的方式有关,如下所示:
I guess this has to do with the way the checkbox is rendered to HTML, which is like this:
<span class="test">
<input id="ctl00_c1_cb1" type="checkbox" name="ctl00$c1$cb1" checked="checked"/>
<label for="ctl00_c1_cb1">Checkbox XYZ</label>
</span>
如何正确设置点击事件处理程序以防止它被调用两次?
How do I correctly setup the click event handler to prevent it from being called twice?
推荐答案
好吧,再次阅读我的问题后,我找到了解决方法.
Well after reading my question again, I found a way how to solve it.
只需将输入"添加到 jQuery 选择器:
Just add "input" to the jQuery selector:
<script type="text/javascript">
$(document).ready(function() {
$('.test input').click(function() {
alert("click")
})
});
</script>
这篇关于jQuery 单击事件处理程序为复选框调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文