【问题标题】:Javascript console.log() running additional code [duplicate]Javascript console.log() 运行附加代码 [重复]
【发布时间】: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


【解决方案1】:

此行错误:document.getElementById("test_button").addEventListener("click", console.log(to_print));

你没有定义回调,你调用了 console.log 函数。

正确:document.getElementById("test_button").addEventListener("click", ()=&gt;console.log(to_print));

document.getElementById("test_button").addEventListener("click", function() {console.log(to_print)});

【讨论】:

  • 或更简单:document.getElementById("test_button").addEventListener("click", console.log.bind(null, to_print));
  • @quirimmo 这并不容易,只是短了 1-2 个字符......
  • @quirimmo 为什么这更容易?是的,这也是一个解决方案,但更容易吗? ()=&gt;console.log() 很简单,或者?
  • @inf3rno 我发现这更容易,这是他们发明bind 方法的原因之一。此外,您没有定义任何其他不需要的额外功能
  • @quirimmo 这不是真的。这不是为什么发明bind 的原因,并且:定义 lambda 函数有什么问题? bind 还定义了一个 new 函数(在内存中)。所以我看不到使用绑定箭头函数的好处。
猜你喜欢
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多