我正在编写一个脚本,将一本书作为一些句子。我想打印每个句子,然后使每个句子可点击。现在,我已经打印了每个句子,但是当我尝试用
元素附加每个句子的唯一ID时,它就不起作用了。这是我的jsfidde:http://jsfiddle.net/mvvq8L7p/
相关的代码段。
var IdCounter = 0;
for (var i = 0, len = book_sentences.length; i < len; i++) {
IdCounter++;
document.getElementById("pageOfBook").innerHTML = "<p class='sentence' id='sentence#" + IdCounter + "'>" + book_sentences[i] + "</p>";
}
任何人都可以解释为什么会发生这种情况以及如何使其发挥作用?在此先感谢,我非常感谢您的帮助!
答案 0 :(得分:2)
只需将您的段落拆分为'。',然后使用IDCounter /
将其附加到您的div
var book = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
var book_sentences = book.split('.');
IdCounter = 0;
book_sentences.forEach(function(data){
IdCounter = IdCounter + 1;
console.log(data);
document.getElementById("pageOfBook").innerHTML += "<p class='sentence' id='sentence#" + IdCounter + "'>" + data + ".</p>";
});
<div id="pageOfBook"></div>