onclick事件在点击按钮之前触发 - javascript [英] onclick event fires before button clicked - javascript

查看:1484
本文介绍了onclick事件在点击按钮之前触发 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带按钮的弹出窗口。当我点击按钮时我想要发生一些事情,请说出警告。

I have a pop up window with a button. When I click the button I want something to happen, say an alert.

我遇到的问题是,弹出窗口启动时onclick事件会立即触发单击按钮时。

The issue I am having is that the onclick event fires as soon as the popup is launched and not when the button is clicked.

这是代码。任何想法都将不胜感激。

Here is the code. Any thoughts will be much appreciated.

var popup = open("", "Popup", "width=300,height=200");
var btn = popup.document.createElement("button");
btn.style.height = "50px";
btn.style.width = "150px";
popup.document.body.appendChild(btn);

btn.innerHTML="button1";
btn.onclick = alert("hello");


推荐答案

在你的代码中

btn.onclick = alert("hello");

onclick未被触发。只需 alert 即可立即执行。你应该把它包装成一个函数:

onclick is not fired. Just alert is executed immediately. You should wrap it into a function:

btn.onclick = function(){ alert("hello");}

这篇关于onclick事件在点击按钮之前触发 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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