I have two js files. First one (alert.js)
function test() {
var name= document.getElementById("name").value;
alert(name);
};
and second one (main.js)
document.getElementById("question_button").addEventListener("click", test());
in html i looks like that
<body>
...
<script type="text/javascript" src="js/alert.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
Function test is invoked when page is loaded. It's not what I need. It's probably very simple but I dont get it. How to make function "test" invoke only when button is pressed?
答案 0 :(得分:2)
You're calling test()
and passing the value it returns ( undefined
) to addEventListener
. Just pass test
directly as an argument instead of calling it:
document.getElementById("question_button").addEventListener("click", test);
or pass in an anonymous function:
document.getElementById("question_button").addEventListener("click", function ( ) { test(x) } );