【问题标题】:javascript- Trying to add inner html and then click on it doesn't workjavascript-尝试添加内部html然后单击它不起作用
【发布时间】:2018-05-07 20:41:18
【问题描述】:

我正在尝试将内部 html 添加到 div 元素,然后动态添加点击事件。它提醒 1 但不提醒 2:

alert(wordsGeneral.length); //prints 9
for (var i = 0; i < wordsGeneral.length; i++)
{
    var word = wordsGeneral[i];
    if (wordsToCorrect[word]!= undefined)
    {

        document.getElementById("text").innerHTML += "<u id=\"" + i + "\" style=\"text-decoration: underline;text-decoration-color: red;\">" + word + "</u>";
        alert("1");
        document.getElementById(i).addEventListener("click", function () {
            alert("2");
        });
    }
}

有人可以帮忙吗?

【问题讨论】:

  • 什么是i?你能发布更多你的代码吗?
  • 我想我知道问题出在哪里,但在确定之前我不想发布答案,您能否编辑您的问题以显示i 的定义和使用方式?跨度>
  • 我刚刚编辑了这个。你能说说你的想法吗?

标签: javascript html onclicklistener innerhtml addeventlistener


【解决方案1】:

似乎工作得很好:

i = 1;
word = i;
document.getElementById("text").innerHTML += "<u id=\""+i+"\" style=\"text-decoration: underline;text-decoration-color: red;\">" + word + "</u>";
alert("1");
document.getElementById(i).addEventListener("click", function () {
    alert("2");
});
&lt;div id="text"/&gt;

我会您没有使用 HTML5,并且i 是一个数字,在 HTML4 中是无效的:

ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 (" _")、冒号 (":") 和句点 (".")。

【讨论】:

  • 这似乎是最合乎逻辑的答案,OP给出的信息很少。
  • 谢谢,但即使我在两行中都将 id 更改为 AAA,但它不起作用。 BTW var word 例如是“名称”。
【解决方案2】:

每次分配给容器的innerHTML 时,对容器内元素的任何 Javascript 引用都会被销毁。当您执行something.innerHTML += 时,解释器会执行以下操作:

(1) 以字符串形式检索容器的当前innerHTML

(2) 清除容器内容

(3) 将字符串与您添加的任何内容连接起来

(4) 用新字符串分配给容器的innerHTML

因此,如果您在容器内有一个元素并为它分配了一个事件侦听器,如果您曾经分配(或连接到)容器的innerHTML,则该侦听器将丢失;容器的整个内部结构将从 HTML 字符串中重新解析。

这种事情至少有两种很好的解决方案:

  • 不要附加 HTML 字符串,尤其是在处理用户输入时。相反,创建 元素 并将它们附加到容器中:

const text = document.querySelector('#text');
const wordsGeneral = ['foo', 'bar', 'baz'];
for (let i = 0; i < wordsGeneral.length; i++) {
  const word = wordsGeneral[i];
  text.insertAdjacentHTML('beforeend', "<u id=\"" + i + "\" style=\"text-decoration: underline;text-decoration-color: red;\">" + word + "</u>");
  document.getElementById(i).addEventListener("click", function() {
    alert("2");
  });
}
&lt;div id="text"&gt;&lt;/div&gt;

另一种方法是使用appendAdjacentHTML 方法,它是为这类事情设计的,不会取消引用容器中的其他元素:

const text = document.querySelector('#text');
const wordsGeneral = ['foo', 'bar', 'baz'];
for (let i = 0; i < wordsGeneral.length; i++) {
  var word = wordsGeneral[i];
  const u = text.appendChild(document.createElement('u'));
  u.id = i;
  u.style.cssText = 'text-decoration: underline;text-decoration-color: red;';
  u.textContent = word;
  u.addEventListener("click", function() {
    alert("2");
  });
}
&lt;div id="text"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2021-08-28
    • 2013-05-29
    • 2017-07-06
    相关资源
    最近更新 更多