javascript - 使用 Uniqe ID 添加段落数组中的句子

标签 javascript jquery html

我正在编写一个脚本,将一本书作为一些句子数组。我想打印每个句子,然后使每个句子可点击。现在,我让它打印每个句子,但是当我尝试为每个句子附加一个

元素及其自己的唯一 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>";
}

任何人都可以解释为什么会发生这种情况以及如何使其发挥作用吗?预先感谢,我非常感谢您的帮助!

最佳答案

只需用“.”分隔段落,然后使用 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>

关于javascript - 使用 Uniqe ID 添加段落数组中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28689216/

相关文章:

javascript - Materializecss collapsibles 无法正常工作

javascript - 检查文本区域是否为空

javascript - ajax 创建的输入元素的值在提交时变为 null

jquery - jQuery 中的parent() 和closest() 如何工作?

javascript - 如何使用jQuery存储前端数据?

javascript - div 刷新在 ie8 下不能正常工作

javascript - 选择选择器插件 Bootstrap 下拉列表不适用于手机/平板电脑

javascript - 我可以避免在路由更改时重新渲染父路由处理程序组件吗?

javascript - 所选文本在 640 像素或更小的视口(viewport)中逐渐消失

javascript - html 表单不响应点击 "enter"按钮