访问在另一个文件中创建的按钮 - javascript

时间:2014-04-23 11:07:43

标签: javascript jquery

我正在尝试在外部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>

1 个答案:

答案 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}}

Demo