addEventListener gone after appending innerHTML

前端 未结 2 556
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 02:22

Okay, so i have the following html added to a site using javascript/greasemonkey. (just sample)

  • HEllo<
相关标签:
2条回答
  • 2020-12-02 02:40

    U can also use jQuery's 'live' function

    0 讨论(0)
  • 2020-12-02 02:44

    Any time you set the innerHTML property you are overwriting any previous HTML that was set there. This includes concatenation assignment, because

    element.innerHTML += '<b>Hello</b>';
    

    is the same as writing

    element.innerHTML = element.innerHTML + '<b>Hello</b>';
    

    This means all handlers not attached via HTML attributes will be "detached", since the elements they were attached to no longer exist, and a new set of elements has taken their place. To keep all your previous event handlers, you have to append elements without overwriting any previous HTML. The best way to do this is to use DOM creation functions such as createElement and appendChild:

    var menu = pmgroot.getElementsByTagName("ul")[0];
    var aEl  = document.createElement("a");
    aEl.innerHTML = "Hello";
    aEl.id "123";
    menu.appendChild(aEl);
    
    0 讨论(0)
提交回复
热议问题