search

Home  >  Q&A  >  body text

javascript - jq click event repeated execution problem

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?

曾经蜡笔没有小新曾经蜡笔没有小新2739 days ago1063

reply all(9)I'll reply

  • 漂亮男人

    漂亮男人2017-07-05 10:40:45

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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:40:45

    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();
    });

    reply
    0
  • 某草草

    某草草2017-07-05 10:40:45

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:40:45

    Is this bubbling? e.stopPropagation()

    reply
    0
  • typecho

    typecho2017-07-05 10:40:45

    off Unbind first, then bind

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 10:40:45

    $('document').unbind('click').click(function() {
                //dosomething
                })

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 10:40:45

    function removeMaopao(ev){
            var eEvent = ev || event;
            eEvent.stopPropagation() && eEvent.stopPropagation;
            return false;
        }
    

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:40:45

    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();
    });

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 10:40:45

    Remember to turn off() after on()

    reply
    0
  • Cancelreply