Javascript:在页面加载而不是 onclick/onsubmit 时调用函数 [英] Javascript: Functions get called on page load instead of onclick/onsubmit

查看:22
本文介绍了Javascript:在页面加载而不是 onclick/onsubmit 时调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 JS 比较陌生,但我以前用 C 编程过,我正试图了解它的整个事件驱动性质.我正在尝试创建一个脚本来验证表单输入,但是我的所有代码都在运行——if/else 中的所有内容、循环、你有什么——无论事件是否发生.为了测试,为了方便发帖,我写了一个简单的程序,也有这个问题.

I'm relatively new to JS, but I have programmed in C before, and I'm trying to get my head around the whole event driven nature of it. I'm trying to create a script that will validate form input, however all of my code is being run - everything inside if/else, loops, what have you - regardless of the event happening or not. To test, and to make it easier to post here, I've written a simple program that has this problem too.

HTML:

<button id="test">Test</button>

Javascript:

Javascript:

function init(){
    document.getElementById("test").onclick = alert("hello");
}

window.onload = init;

据我了解,应该在页面加载时调用 init 函数(window.onload),并在单击 ID 为test"的按钮时弹出警报(onclick).实际发生的是,一旦页面加载,警报就会弹出,如果我点击按钮,它会再次弹出.

From what I understand, the init function should be called when the page loads (window.onload), and the alert should pop up when the button with the ID "test" is clicked (onclick). What is actually happening is that the alert is popping up as soon as the page loads, and will pop up again if I hit the button.

我的想法是我对 JS 的执行顺序做出了一些错误的假设,但我想不出那是什么.有人能对此有所了解吗?

My thinking is that I've made some incorrect assumptions about the order in which JS is executed, but I cant think of what that is. Is anyone able to shed some light on this?

推荐答案

不对,应该是:

function init(){
    document.getElementById("test").onclick = function () { alert("hello"); };
}

这是因为您需要在 JavaScript 中将函数本身分配给 click 事件(alert 是一个函数).

This is because you need in JavaScript you need to assign the function itself to the click event (alert is a function).

以此为例:

function hello() {
    alert("hello");
}

document.getElementById("test").onclick = hello;

注意我没有把括号()放在hello函数后面?那是因为我使用了对函数本身的引用.如果我加上括号,我实际上是在点击分配发生的时间点评估该功能.

Note that I didn't put the brackets () after hello function? That's because I'm using a reference to the function itself. If I put the brackets, I'm actually evaluating that function at the point in time of the click assignment happening.

这样做:

document.getElementById("test").onclick = hello();

将显示警报将在此行执行后alert 立即显示.

Will show the alert will show the alert immediately after this line has been executed.

这篇关于Javascript:在页面加载而不是 onclick/onsubmit 时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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