Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

asp.net - jQuery click event handler is called twice for a checkbox

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" />

In the browser (FF3.5 / IE8) I have the following problem:

  • if I click the checkbox (the small square), it works as expected
  • if I click the checkbox's text ("Checkbox XYZ"), then the click event is fired twice, and the alert is shown twice.

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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I have just experienced the same thing, but am not sure that event bubbling is causing my issue. I have a custom tree control, and when an item is opened, I use $(id).click() to attach a handler to all elements of a certain kind.

I suspect that this means that existing items elsewhere that already have the event, may then have it added again. I found that unbinding everything then re-binding solved my problem, thus:

$('img.load_expand').unbind("click").click(function()
{
  // handler
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...