How to append data to div using JavaScript?

前端 未结 11 1942
忘了有多久
忘了有多久 2020-11-22 09:39

I\'m using AJAX to append data to div element, where I fill the div from JavaScript, how can I append new data to the div without losing the previous data found in div?

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 10:27

    Beware of innerHTML, you sort of lose something when you use it:

    theDiv.innerHTML += 'content';
    

    Is equivalent to:

    theDiv.innerHTML = theDiv.innerHTML + 'content';
    

    Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.

    If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):

    var newNode = document.createElement('div');
    newNode.innerHTML = data;
    theDiv.appendChild(newNode);
    

提交回复
热议问题