脚本不等待onclick事件 [英] Script doesn't wait for onclick event

查看:76
本文介绍了脚本不等待onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,为什么标题文本会在页面加载时发生变化,而不仅是在单击按钮后才发生变化?

In the code below, why does the header text change on page load, and not only after the button is clicked?

<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
  function change_text(target_id, target_text) {
    document.getElementById(target_id).textContent = target_text;
}

button1 = document.getElementById("btn1")
button1.onclick = change_text("header", "something")
</script>

推荐答案

问题是此行:

button1.onclick = change_text("header", "something")

JS引擎将按以下顺序执行以下操作:

The JS engine will do the following in this order:

  1. 使用参数"header""something"
  2. 调用change_text
  3. change_text(在本例中为undefined)的结果分配给button1.onclick
  1. Call change_text with the arguments "header" and "something"
  2. Assign the result of change_text (in this case, undefined) to button1.onclick

简·多伊(Jane Doe)的答案应该有效.如果要保留当前的代码结构,则可以使用以下代码:

Jane Doe's answer should work. If you want to keep your current code structure, then you could use the following:

button1.onclick = function(){
    change_text("header", "something");
};

这会创建匿名函数并将其分配给onclick.触发onclick时,它将执行调用change_text的功能.

This creates an anonymous function and assigns it to onclick. When onclick is triggered, it will execute the function which calls change_text.

这篇关于脚本不等待onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆