【发布时间】:2017-09-25 22:10:22
【问题描述】:
我有一些 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 在 cmets 中提到的那样,按钮元素默认充当提交。要获得一个不触发表单动作但可用于调用其他 javascript 的按钮,可以使用:
<input type="button" value="text on the button">
进行上述两项更改后,代码可以正常运行。
谢谢大家的建议。
【问题讨论】:
-
您正在调用 console.log 并将其返回的内容分配给单击事件侦听器。
标签: javascript logging console