[英]Code not working: Using Javascript to dynamically add items to a list in HTML
編輯:JSFiddle指示代碼本身是好的。 任何人都可以對為什么它可能無法作為chrome擴展正確執行進行深入了解嗎?
我正在嘗試為自己制作一個簡單的待辦事項列表Chrome擴展程序。 這是我的代碼:
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
<title>To-Do-List</title>
<script src="popup.js"></script>
</head>
<body>
<div id="header"><h3 id="headtext">TO DO LIST</h3></div>
<form>
<input type="text" id="textbox" placeholder="Input"></input>
</form>
<button id="add">Add</button>
<p>TO DO LIST:</p>
<ul id="myList">
</ul>
</body>
</html>
和Javascript:
<script type="text/javascript">
document.getElementById("add").addEventListener("click", function(){
var node = document.createElement("li");
var textnode = document.createTextNode(document.getElementById("textbox").value);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
)
</script>
當我在輸入字段中輸入文本然后單擊按鈕時,什么也沒有發生。
我通過添加window.onload函數對您的代碼進行了一些修改。
見下文。 現在有效。
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
<title>To-Do-List</title>
<script src="popup.js"></script>
<script type="text/javascript">
window.onload = function(){
document.getElementById("add").addEventListener("click", function(){
var node = document.createElement("li");
var textnode = document.createTextNode(document.getElementById("textbox").value);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
)
};
</script>
</head>
<body>
<div id="header"><h3 id="headtext">TO DO LIST</h3></div>
<form>
<input type="text" id="textbox" placeholder="Input"></input>
</form>
<button id="add">Add</button>
<p>TO DO LIST:</p>
<ul id="myList">
</ul>
</body>
</html>
嘗試這個:
window.onload = function () {
document.getElementById("add").addEventListener("click", function() {
var node = document.createElement("li");
var text = document.getElementById("textbox").value;
node.innerHTML = textnode;
document.getElementById("myList").appendChild(node);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.