我有一些javascript应该将字符串打印到控制台,但是它也会执行另一个在别处定义的函数。脚本是:
var run_once = function() {
console.log("run_once has executed.");
};
var to_print = "This should print.";
run_once();
document.getElementById("test_button").addEventListener("click", console.log(to_print));
HTML:
<!DOCTYPE html>
<html>
<body>
<form method="post">
<button id="test_button">test</button>
</form>
<script src="../scripts/drill_creator.js"></script>
</body>
</html>
刷新页面后,我将以下内容打印到控制台:
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
然后在单击test_button时,控制台显示:
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
run_once has executed. drill_creator.js:2
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
为什么在发生点击时会调用run_once?另外,为什么“这应该打印”。页面加载但是没有点击按钮时打印?
非常感谢
迈克尔
编辑: 我已将最后的javascript行更改为:
document.getElementById("test_button").addEventListener("click", function(){console.log(to_print)});
这解决了在页面加载时触发事件的问题(非常感谢Joshua K)但是这仍然导致在单击按钮时调用run_once。加载后,显示下面的前两行,然后单击按钮,显示接下来的三行:
run_once has executed. drill_creator.js:2
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
This should print. drill_creator.js:8
Navigated to file:///C:/Users/micha/Google%20Drive/k-drills/Source/html/drill_creator.html
run_once has executed. drill_creator.js:2
第二次编辑:
正如Joshu K在对他的回答的评论中提到的那样,按钮元素默认用作提交。要获得一个不触发表单操作的按钮,但可以用来调用其他javascript,可以使用:
<input type="button" value="text on the button">
在完成上述两项更改后,代码的功能正如我所希望的那样。
谢谢大家的建议。
答案 0 :(得分:1)
这一行错误:document.getElementById("test_button").addEventListener("click", console.log(to_print));
你没有定义回调,你可以调用console.log函数。
正确:document.getElementById("test_button").addEventListener("click", ()=>console.log(to_print));
或
document.getElementById("test_button").addEventListener("click", function() {console.log(to_print)});