In-page JavaScript stops when I use document.body[removed] += newHtmlText

后端 未结 3 1443
天命终不由人
天命终不由人 2020-12-07 06:15

Does anyone know why if you use document.body.innerHTML += \"content\"; the JavaScript on the page stops working? I have the following code:



        
3条回答
  •  醉酒成梦
    2020-12-07 07:12

    document.body.innerHTML += "content"; 
    

    Does three things:

    1. Reads the value of innerHTML
    2. Modifies that value
    3. Overwrites innerHTML with the new value

    This deletes the page and then creates a new one.

    Since script elements inserted with innerHTML are not executed, this kills the JS.


    Don't append data using innerHTML. Generate DOM nodes (with createElement, createTextNode and friends) and then append them (with appendChild, insertBefore and so on).

提交回复
热议问题