我正在尝试在外部javascript文件中声明的函数中创建一个按钮。使用html文件(在某种意义上是“主”文件),我试图访问此按钮并分配单击侦听器。我无法这样做。请看下面我的代码到目前为止。
testDialogJS.js
:
/**
* The JS here will be referenced from another file.
*/
function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "Button");
btn.appendChild(text);
}
testDialog.html:
<html>
<head>
<style>
.hlight{background-color:#ffcc00; }
textarea {
width:100%;
height:100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"/>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script> -->
<script type="text/javascript" src="testDialogJS.js"></script>
<script type="text/javascript">
window.onload=function() {
console.log("Window has been loaded.");
creator(); //this function is elsewhere.
var btn = document.getElementById("Button");
if(btn == null) {
console.log("Button is null.");
} else {
console.log("Button is not null.");
btn.onclick=function() {
console.log("Hello.");
}
}
}
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
appended
button
document
null
。因此,当您尝试使用document.getElementById("Button")
creator()
在function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "mybtn");
btn.appendChild(text);
document.body.appendChild(btn);
}
中添加以下语句
{{1}}