2017-05-09 80 views
0

我在将按钮放入以下代码时出现问题。 这是一个Javascript计划,我在控制台中的错误消息说:按钮在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,我一定会犯一些初学者的错误。但那个错误在哪里?

+0

Your're在事件处理程序中使用'document.write'。该事件处理程序在页面加载并关闭“文档”后调用。因此,在这一点上调用'document.write'将会覆盖原先存在的内容而不是追加它。 –

回答

1

问题是您在事件处理程序中使用document.writedbRef.on("value", ...)。所以你是在异步调用它,这意味着文档在这个时候是关闭的。因此document.write将隐含地调用document.open,这会清除当前页面,删除那里的所有内容(特别是您的按钮)。

而不是使用document.write添加内容到文档,使用DOM操作。例如,附加新段落的页面,你可以这样做:

var p = document.createElement("p"); 
p.innerHTML = "Hello <b>world!</b>"; 
document.body.appendChild(p); 
1

https://developer.mozilla.org/en-US/docs/Web/API/Document/write

看看第一个音符:” ......在一个封闭的(加载)文件,要求文件撰写自动调用document.open,它将清除文档。“

您的事件处理程序在页面加载后一段时间被调用,意味着document已关闭。

而不是使用document.write,您应该直接操作DOM,方法是使用document.createElement()创建元素并将其与.appendChild()相加。
虽然它的作用是添加按钮document.write,因为它在页面加载时已经完成并且document仍然打开,所以一般来说,避免document.write是一个好主意,因此您应该考虑添加DOM按钮。