2014-04-23 8 views
0

외부 자바 스크립트 파일에 선언 된 함수에서 버튼을 만들려고합니다. html 파일 (어떤 의미에서는 "주"파일)을 사용하여이 버튼에 액세스하고 클릭 리스너를 지정하려고합니다. 나는 그렇게 할 수 없다. 지금까지 가지고있는 코드는 아래를 참조하십시오. 다른 파일에서 생성 된 버튼에 액세스 - javacript

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

처럼 creator()에 다음 문을 추가 document.getElementById("Button")

를 사용하여 버튼을 선택하려고 할 때 그래서이 null 반환? – Arvind

+0

@Arvind : 네가 옳았다. 문서에 버튼을 추가하지 않았습니다. 답변을 작성할 수 있다면 기꺼이 올바른 것으로 표시해 드리겠습니다. 감사! – Sriram

답변

1

당신은하지 appended 당신의 buttondocument에 있습니다. 당신이 문서에 그 버튼을 추가 않은이

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); 
} 

Demo

관련 문제