function show() {
var todos = get_todos();
var html = '<ul>';
for(var i=0; i<todos.length; i++) {
html += '<li>' + todos[i] + ' <button class="remove" id="' + i + '">Delete</button></li>';
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
在此代码中,我想分开&#39; ul和li&#39; html页面上的结构。你能帮帮我吗?
答案 0 :(得分:1)
如果您想要一些代码var battlefieldOne_Comments = require('../models/comments').battlefieldOneComments;
var anotherGame_Comments = require('../models/comments').anotherGameComments;
您可以使用html
查看来自html的js查看下面的plunker
您也需要该脚本,因为您正在使用脚本动态添加li
例如: script tag
<强>步骤:强>
<script src = "script.js"></script>
元素。 ul
附加到li
元素。 ul
script tag
&#13;
function show() {
var ul = document.getElementById('list');
var html = '';
var todos = ["Saab", "Volvo", "BMW"];
for(var i=0; i<todos.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(todos[i]));
ul.appendChild(li);
};
ul.append(html);
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
&#13;
请运行以上代码段
答案 1 :(得分:0)
我认为您想要的是一个HTML模板,您可以重复使用它并与JS代码分开。一种流行的模板引擎是handlebars.js。
实现这一目标的步骤是:
<div>
是一种方法。这将是这样的:
var todoListSource = document.getElementById("todoList").innerHTML;
var todoList = Handlebars.compile(todoListSource);
var items = ["Item 1", "Item 2", "Item 3", "Item 4"];
var todoContainer = document.getElementById("todo");
todoContainer.innerHTML = todoList(items);
// event delegation - use the same event handler for all buttons
// modified from https://stackoverflow.com/a/24117490/18771
todoContainer.addEventListener('click', function (e) {
if (!e.target.matches('.deleteTodo')) return;
e.stopPropagation();
var li = e.target.parentElement;
li.parentElement.removeChild(li);
});
.template {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<div id="todo"></div>
<div class="template" id="todoList">
<ul>
{{#each .}}
<li>
<span>{{.}}</span>
<button class="deleteTodo">delete</button>
</li>
{{/each}}
</ul>
</div>
使用jQuery可以简化JS部分。
var todoList = Handlebars.compile($("#todoList").html());
var items = ["Item 1", "Item 2", "Item 3", "Item 4"];
$("#todo").html(todoList(items));
// event delegation - use the same event handler for all buttons
$("#todo").on('click', '.deleteTodo', function (e) {
e.stopPropagation();
$(this).closest('li').remove();
});
.template {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="todo"></div>
<div class="template" id="todoList">
<ul>
{{#each .}}
<li>
<span>{{.}}</span>
<button class="deleteTodo">delete</button>
</li>
{{/each}}
</ul>
</div>