我在以下代码中放置按钮时遇到问题。 这是一个 Javascript 程序,我在控制台中收到一条错误消息:
ReferenceError: myClickFunc is not defined
而这个功能就在我眼前。下面是相关代码。
我最近发表了类似的帖子,但没有得到答案,但我得到了一些提示并做了更多研究以解决问题。这是我目前的情况。
以下代码行前的按钮:
dbRef.on("value", function(snapshot)
可以正常工作,但很快就会消失。其他按钮(循环内)会产生上述错误消息。我注意到的另一件事是该页面似乎永远不会结束加载。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web application</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script>
function someCallingFunc(timeRef,work)
{/* Beginning of someCallingFunc */
var workRef = timeRef.child(work)
workRef.on("value", function(workSnapshot) {
var rcdData = workSnapshot.val();
document.write("English name: " + rcdData["engName"] + "<br/>\n");
document.write("<input type='Submit' value='Edit' onClick='myClickFunc()'><br/>\n");
});
}/* End of someCallingFunc */
function myClickFunc()
{/* Beginning of myClickFunc */
window.open("http://www.google.com");
}/* End of myClickFunc */
var config = {
apiKey: ".........",
authDomain: "..........firebaseapp.com",
databaseURL: "..........firebaseio.com",
projectId: ".........",
storageBucket: "..........appspot.com",
messagingSenderId: "........."
};
firebase.initializeApp(config);
var dbRef = firebase.database().ref().child('DataList');
// This button works but only appears for half a second, then disappears.
document.write("<button onClick='myClickFunc()'>EDIT</button><br/>\n");
dbRef.on("value", function(snapshot) {
for (number in snapshot.val()) {
document.write("Year " + number + " :<br/>\n");
var numberRef = dbRef.child(number)
numberRef.on("value", function(numberSnapshot) {
for (work in numberSnapshot.val()) {
someCallingFunc(numberRef,work);
document.write("<br/>\n");
}
});
}});
</script>
</body>
</html>
我尝试以各种方式更改 myClickFunc() 的位置,但没有成功。
我对 JS 的经验不是很丰富,我一定犯了一些初学者的错误。但这个错误在哪里呢?
最佳答案
问题是您正在使用 document.write
在事件处理程序中 (dbRef.on("value", ...
)。因此您异步调用它,这意味着文档此时已关闭。因此 document.write
将隐式调用 document.open
,这会清除当前页面,删除那里的所有内容(特别是您的按钮)。
不要使用 document.write
向文档添加内容,而是使用 DOM 操作。例如,要将新段落附加到页面,您可以执行以下操作:
var p = document.createElement("p");
p.innerHTML = "Hello <b>world!</b>";
document.body.appendChild(p);
关于javascript - Javascript 中按钮消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866559/