jQuery click event handler is called twice for a checkbox

前端 未结 10 1935
野趣味
野趣味 2020-12-09 17:08

I have a problem with the following code in an ASPX page:



        
相关标签:
10条回答
  • 2020-12-09 17:37

    The function runs twice. Once from the inside and then it gets called again from inside itself. Simple add a return statement at the end.

    <script type="text/javascript">
    $(document).ready(function() {
        $('.test').click(function() {
            alert("click");
            return false;
        })
    });
    </script>
    
    <asp:CheckBox runat="server" Text="Checkbox XYZ" CssClass="test" ID="cb1" />
    

    This worked perfectly for me.

    0 讨论(0)
  • 2020-12-09 17:39

    I think it's because a <label> with a for attribute raises the click event of <input type="radio"> or <input type="checkbox"> element that is associated for when clicked.

    So in your jQuery code, you set up a click event handler for both the <label> and the <input> inside <span class="test">. When clicking on the <label>, the click event handler that you set up on the label will execute, then the click event handler set up on the <input> will execute when the label raises the click event on the <input>.

    0 讨论(0)
  • 2020-12-09 17:40
    $(document).ready(function() {
        $('.test').click(function(event) {
                        event.stopImmediatePropagation();
                        alert("Click");
                        })
                     }
                  );
    

    I was able to get my code working by stopping the event Propagation. It did not affect the status change of the checkbox.

    0 讨论(0)
  • 2020-12-09 17:45

    What you are seeing is event bubbling. The click event is first handled by the label and is then passed on to the checkbox. You get one alert for each. To prevent event bubbling you need to return false in your click handler.

    $(document).ready(function() {
            $('.test').click(function() {
                    alert("Click");
                    return false;
            })
    });
    

    However while this prevents event bubbling it also has the undesirable side effect of preventing the checkbox from changing state. So you'll need to code around that.

    0 讨论(0)
提交回复
热议问题