OnClick仅适用于最后添加的子项

时间:2016-12-22 17:45:20

标签: javascript dom

我有这样的代码:

var pageCount = 5; //for example, doesn't really matter
var paginationList = document.createElement("ul");
paginationList.className = "pagination";
for(var i = 1; i <= pageCount; i++){
  var paginationNode = document.createElement("li");
  var paginationLink = document.createElement("a");
  paginationLink.innerHTML = i;
  paginationLink.href = "#";
  paginationLink.onclick = function(){ console.log("yay"); }; //removed loadProperties here
  paginationNode.appendChild(paginationLink);
  paginationList.appendChild(paginationNode);
}
divxml.innerHTML = "";
divxml.appendChild(paginationList);
//code replaced by this comment inserts a lot of content to divxml
//for this bug or something to work, you need next line
divxml.innerHTML += "<br>";
divxml.appendChild(paginationList);

正如你所看到的,我在这里做分页。问题是第一个分页按钮不起作用,当我点击它时,我无法在控制台中看到yay,但第二个和最后一个分组按钮确实有效(我看到yay在我点击它们的控制台中)。什么错了,我该如何解决?

2 个答案:

答案 0 :(得分:0)

divxml.innerHTML += "<br>";

innerHTML读取将DOM转换为HTML。 HTML没有附加到DOM的事件处理程序。

将HTML写回innerHTML(在向其附加<br>之后)将HTML转换为DOM并覆盖之前的DOM。

您现在已经销毁了事件处理程序。

请勿使用innerHTML

答案 1 :(得分:0)

您必须创建两个列表元素和两组列表项元素才能使其正常工作:

var pageCount = 5; //for example, doesn't really matter
var paginationList1 = document.createElement("ul");
var paginationList2 = document.createElement("ul");
paginationList1.className = paginationList2.className = "pagination";

for(var i = 1; i <= pageCount; i++){
  paginationList1.appendChild(createPaginationLink(i));
  paginationList2.appendChild(createPaginationLink(i));
}

document.body.appendChild(paginationList1);
document.body.appendChild(document.createElement("br"));
document.body.appendChild(paginationList2);

function createPaginationLink(text) {
  var paginationNode = document.createElement("li");
  var paginationLink = document.createElement("a");
  paginationLink.innerText = text;
  paginationLink.href = "#";
  paginationLink.addEventListener("click", function(){ console.log("yay"); }); //removed loadProperties here
  paginationNode.appendChild(paginationLink);
  return paginationNode;
}

正如另一个答案中所述,变异innerHTML将导致您的元素在没有事件侦听器的情况下重新创建,因此请使用<br/>创建并附加您的createElement元素, appendChild

Codepen