gpt4 book ai didi

javascript-尝试添加内部 html 然后单击它不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:04 24 4
gpt4 key购买 nike

我正在尝试将内部 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 = 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");
});
<div id="text"/>

我会猜测您没有使用 HTML5,而 i 是一个数字,这在 HTML4 中是无效的:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

关于javascript-尝试添加内部 html 然后单击它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com