【问题标题】:JS: Avoiding modifications of ".innerHTML"JS:避免修改“.innerHTML”
【发布时间】:2016-02-17 23:28:36
【问题描述】:

我有一些<div>,我一直在其中添加新对象。 这些对象被分配了监听器。

问题是当我使用.innerHTML 添加这些新对象时,之前的监听器会丢失。

是否可以创建一个表示 HTML 对象的 JS 字符串,并在没有.innerHTML += ... 的情况下将其作为子对象附加?

我举个例子:

var line_num = 0;
function addTextLine(line) {
    var lineId = "line_" + line_num;
    var lineHtml = "<p id = '" + lineId + "'>" + line + "</p>";
    document.getElementById("some_div_id").innerHTML += lineHtml;
    document.getElementById(line_id).addEventListener("click", function() {
        alert("hello");
    });
    line_num += 1;
}

some_dive_idinnerHTML的修改,移除了旧的&lt;p&gt;对象的事件监听器。

那么 - 是否可以将 &lt;p&gt; HTML 字符串转换为对象,从而将其附加到 some_div_id 而不修改其 .innerHTML

【问题讨论】:

  • 您可以使用DOM APIs like .appendChild() 向 DOM 添加新节点。
  • 但是如何将文本&lt;p&gt;...&lt;/p&gt; 转换为可附加对象?
  • 使用像createElement()setAttribute()这样的API。
  • 你能举个例子吗?
  • 很难想出更好的理由不使用 HTML 作为使用 innerHTML 插入的字符串。

标签: javascript html


【解决方案1】:

您的问题是 innerHtml 擦除然后重新创建当前 DOM 节点;这就是你失去事件监听器的原因。 您可以使用 insertAdjacentHtml 插入您的 html

 document.getElementById("some_div_id").insertAdjacentHTML('afterbegin', lineHtml );

afterbegin 参数确保插入的 html 将是您当前节点的子节点。

在此处查找更多信息:Element.insertAdjacentHTML()

【讨论】:

    【解决方案2】:

    创建元素并附加它

    var p = document.createElement("p");
    p.innerHTML = line;
    p.id = line_id; // or p.setAttribute("id", line_id);
    p.addEventListener("click", function(){ });
    document.getElementById("foo").appendChild(p);
    

    另一个选项可以是创建一个元素,并设置 innerHTML 并从那里读取元素。 (第一种更好)

    var div = document.createElement("div");
    div.innerHTML = lineHtml;
    //now you can either select the children and append it or append the div.
    

    【讨论】:

      【解决方案3】:

      使用element.appendChild().

      您的代码不起作用,因为每次使用 innerHtml += 'Something' 时,您都会删除该特定元素内的任何内容并插入带有添加字符串的旧内容。

      相反,您可以使用函数创建元素并将其附加到父元素。

      重写你的代码应该是:

      var line_num = 0;
      function addTextLine(line) {
        var line = document.createElement('p');
        line.id = "line_" + line_num;
        line.textContent = line;
        line.addEventListener("click", function() {
              alert("hello");
          });
        document.getElementById("some_div_id").appendChild(line);
        line_num += 1;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-03
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 2011-08-22
        相关资源
        最近更新 更多