Is it possible to append to innerHTML without destroying descendants' event listeners?

前端 未结 13 1182
悲哀的现实
悲哀的现实 2020-11-21 23:40

In the following example code, I attach an onclick event handler to the span containing the text \"foo\". The handler is an anonymous function that pops up an <

相关标签:
13条回答
  • 2020-11-22 00:05

    something.innerHTML += 'add whatever you want';

    it worked for me. I added a button to an input text using this solution

    0 讨论(0)
  • 2020-11-22 00:13

    There is another alternative: using setAttribute rather than adding an event listener. Like this:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Demo innerHTML and event listeners</title>
    <style>
        div {
            border: 1px solid black;
            padding: 10px;
        }
    </style>
    </head>
    <body>
        <div>
            <span>Click here.</span>
        </div>
        <script>
            document.querySelector('span').setAttribute("onclick","alert('Hi.')");
            document.querySelector('div').innerHTML += ' Added text.';
        </script>
    </body>
    </html>

    0 讨论(0)
  • 2020-11-22 00:15

    Now, it is 2012, and jQuery has append and prepend functions that do exactly this, add content without effecting current content. Very useful.

    0 讨论(0)
  • 2020-11-22 00:16

    For any object array with header and data.jsfiddle

    https://jsfiddle.net/AmrendraKumar/9ac75Lg0/2/

    <table id="myTable" border='1|1'></table>
    
    <script>
      const userObjectArray = [{
        name: "Ajay",
        age: 27,
        height: 5.10,
        address: "Bangalore"
      }, {
        name: "Vijay",
        age: 24,
        height: 5.10,
        address: "Bangalore"
      }, {
        name: "Dinesh",
        age: 27,
        height: 5.10,
        address: "Bangalore"
      }];
      const headers = Object.keys(userObjectArray[0]);
      var tr1 = document.createElement('tr');
      var htmlHeaderStr = '';
      for (let i = 0; i < headers.length; i++) {
        htmlHeaderStr += "<th>" + headers[i] + "</th>"
      }
      tr1.innerHTML = htmlHeaderStr;
      document.getElementById('myTable').appendChild(tr1);
    
      for (var j = 0; j < userObjectArray.length; j++) {
        var tr = document.createElement('tr');
        var htmlDataString = '';
        for (var k = 0; k < headers.length; k++) {
          htmlDataString += "<td>" + userObjectArray[j][headers[k]] + "</td>"
        }
        tr.innerHTML = htmlDataString;
        document.getElementById('myTable').appendChild(tr);
      }
    
    </script>
    
    0 讨论(0)
  • 2020-11-22 00:18

    Unfortunately, assignment to innerHTML causes the destruction of all child elements, even if you're trying to append. If you want to preserve child nodes (and their event handlers), you'll need to use DOM functions:

    function start() {
        var myspan = document.getElementById("myspan");
        myspan.onclick = function() { alert ("hi"); };
    
        var mydiv = document.getElementById("mydiv");
        mydiv.appendChild(document.createTextNode("bar"));
    }
    

    Edit: Bob's solution, from the comments. Post your answer, Bob! Get credit for it. :-)

    function start() {
        var myspan = document.getElementById("myspan");
        myspan.onclick = function() { alert ("hi"); };
    
        var mydiv = document.getElementById("mydiv");
        var newcontent = document.createElement('div');
        newcontent.innerHTML = "bar";
    
        while (newcontent.firstChild) {
            mydiv.appendChild(newcontent.firstChild);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:19

    I created my markup to insert as a string since it's less code and easier to read than working with the fancy dom stuff.

    Then I made it innerHTML of a temporary element just so I could take the one and only child of that element and attach to the body.

    var html = '<div>';
    html += 'Hello div!';
    html += '</div>';
    
    var tempElement = document.createElement('div');
    tempElement.innerHTML = html;
    document.getElementsByTagName('body')[0].appendChild(tempElement.firstChild);
    
    0 讨论(0)
提交回复
热议问题