gpt4 book ai didi

Javascript console.log() 运行附加代码

转载 作者:行者123 更新时间:2023-11-30 21:08:10 24 4
gpt4 key购买 nike

<分区>

我有一些 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">

进行上述两处更改后,代码如我所愿地运行。

谢谢大家的建议。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com