Onclick()函数正常工作 [英] Onclick() function on working
问题描述
全部!我在使用简单的onclick方法时遇到问题.请帮助我.这是代码...当我单击按钮时,什么都没有发生.
all! I am having a problem using the a simple onclick method. Kindly please help me out. Here is that code... When i click on the button nothing really happens.
window.onload=initall();
var xhr = false;
function initall(){
var btn=document.getElementById('btn');
btn.onclick=alert('hi');
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="testjs.js"></script>
</head>
<body>
<input type="text" required name="id">
<input type="button" id="btn" value="send">
<div id="result"></div>
</body>
</html>
推荐答案
window.onload=initall();
调用函数 initall
,并将 initall
的返回值分配为事件处理程序.也就是说, initall
立即执行,而不是在触发 load
事件时执行.
与 btn.onclick = alert('hi');
相似.但是在两种情况下,返回值都不是函数.
calls the function initall
and assigns the return value of initall
as event handler. That is, initall
is executed immediately and not when the load
event is triggered.
Similar for btn.onclick=alert('hi');
. But in both cases, the return value is not a function.
您必须为这些属性分配功能,然后在事件发生时调用这些属性.
You have to assign functions to those properties, which are then being called when the event occurs.
function initall(){
var btn = document.getElementById('btn');
btn.onclick = function() { // creates and assigns the function at once
alert('hi');
};
}
window.onload = initall; // assign the function reference, no `()`.
我建议阅读quirksmode.org上的优秀教程,以了解事件处理当然,有关JavaScript基础的 MDN JavaScript指南.
I recommend to read the excellent tutorials at quirksmode.org to learn about event handling and of course the MDN JavaScript Guide for the JavaScript basics.
这篇关于Onclick()函数正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!