javascript - jq click event repeated execution problem
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-07-05 10:38:45
0
9
947

Help, the elements dynamically generated by jq need to be bound with on to click events to take effect, and the function that executes on also has click events, and then the function is executed twice. How to solve this situation?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all (9)
漂亮男人

Use the event object to find the target you really want to click

    曾经蜡笔没有小新

    In fact, it is nothing more than the event being bound twice or the event bubbling;
    1. Unbind the event and bind it again

    $(ele).unbind('click').click(function() { // to do })

    2, Cancel bubbling

    $(ele).click(function(e){ e.stopPropagation(); });
      某草草

      Remove monitoring first, then monitor
      .off(handler).on(handler)

        Peter_Zhu

        Is this bubbling? e.stopPropagation()

          typecho

          off Unbind first, then bind

            滿天的星座
            $('document').unbind('click').click(function() { //dosomething })
              过去多啦不再A梦
              function removeMaopao(ev){ var eEvent = ev || event; eEvent.stopPropagation() && eEvent.stopPropagation; return false; }
                Peter_Zhu

                The person above made it clearer.
                1. Found the problem
                1.1 is bound twice, because the dynamically generated element is bound to an event, but in this event the previously bound event is called again

                $('document').unbind('click').click(function() { //取消绑定的回调事件 })

                1.2 It is still caused by the bubbling of events (if you are not familiar with bubbling, please read the relevant information first)

                $('document').click(function(e){ //取消事件冒泡 e.stopPropagation(); });

                2. Dynamically generated elements do not necessarily need to use dynamic binding events

                Event handlers using the delegate() method work on current or future elements (such as new elements created by scripts).
                Click here to view detailed documents: http://www.w3school.com.cn/jq...

                $("p").delegate("button","click",function(){ $("p").slideToggle(); });
                  phpcn_u1582

                  Remember to turn off() after on()

                    Latest Downloads
                    More>
                    Web Effects
                    Website Source Code
                    Website Materials
                    Front End Template
                    About us Disclaimer Sitemap
                    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!