gpt4 book ai didi

javascript - html和js代码如何分离?

转载 作者:行者123 更新时间:2023-12-03 02:07:13 25 4
gpt4 key购买 nike

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);
};
}

在这段代码中,我想分离 html 页面上的“ul 和 li”结构。你能帮我吗?

最佳答案

如果您想要一些代码html,那么您可以做一些事情

您可以使用 script tag 从 html 引用 js 检查下面的骗子

您也需要该脚本,因为您正在使用脚本动态添加 li

例如: <script src = "script.js"></script>

步骤:

  • 我已经获取了一个 html 并创建了一个 ul元素。
  • 创建了一个附加 li 的脚本到ul元素。
  • 使用 script tag 添加了对该脚本的引用

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);
};
}
<!DOCTYPE html>
<html>
<body>
<ul id="list">
</ul>
<p id="demo" onClick="show()">Click ME</p>
</body>
</html>

请运行上面的代码片段

Here is a working demo for the same

关于javascript - html和js代码如何分离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752580/

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