javascript 单击加载事件上的按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11756606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click button on load event
提问by Ebikeneser
I have the following javascript -
我有以下 javascript -
function onLoad() {
if (!(document.applets && document.VLVChart && document.VLVChart.isActive())) {
setTimeout('onLoad()', 200);
return;
}
objChart = document.VLVChart;
PollEvent();
}
function fan() {
objChart.reorganize();
}
And then when the HTML page is loaded -
然后当加载 HTML 页面时 -
<body onLoad="onLoad()">
and have a button within the HTML that execute the fan()
function -
并在 HTML 中有一个按钮来执行该fan()
功能 -
<input type='button' value='Fan' onClick='fan();'>
Is it possible for me to activate the fan()
function within the onload event so that a user does ont have to click the button?
我是否可以fan()
在 onload 事件中激活该功能,以便用户不必单击该按钮?
EDITAfter trying the provided answers, on debugging the code breaks on the line -
编辑尝试提供的答案后,在调试代码中断行时 -
objChart.reorganize();
Within the fan()
function with the error -
在fan()
有错误的函数中 -
SCRIPT5007: Unable to get value of the property 'reorganize': object is null or undefined
This is odd as when I manually click the button on the page, the function works fine.
这很奇怪,因为当我手动单击页面上的按钮时,该功能工作正常。
SolutionAfter much head scratching I have realised that I was trying to load the fan()
function before the page (and more specifically the objChart) had fully loaded. Hence why adding the function in the onLoad
event was not working. I added a setTimeout
-
解决方案经过多次摸索后,我意识到我试图fan()
在页面(更具体地说是 objChart)完全加载之前加载该函数。因此,为什么在onLoad
事件中添加函数不起作用。我加了一个setTimeout
-
function Fan()
{
setTimeout(function(){objChart.reorganize();},3000);
}
采纳答案by Utkanos
<body onload='onLoad(); fan();'>...
However inline JS is best avoided and you would do well to begin looking into centralised event management. There are various advantages to this.
但是最好避免使用内联 JS,您最好开始研究集中式事件管理。这有各种优点。
An answer I wrote yesterdayto another question outlines why this is. Something like jQuery makes this trivial if it's new for you.
我昨天写的另一个问题的答案概述了为什么会这样。如果它对你来说是新的,像 jQuery 这样的东西会让这变得微不足道。
$(function() {
$('body').on('load', function() {
onLoad();
fan();
});
});
回答by feeela
Reading your question I assume you didn't even have tried. Just call that function from within your onLoad()
-function:
阅读您的问题,我认为您甚至没有尝试过。只需从您的onLoad()
-function 中调用该函数:
function onLoad()
{
fan();
/* … */
}
回答by Nick
Yes.
是的。
You can use <body onload='onLoad(); fan();'>
as Utkanos suggests.
您可以<body onload='onLoad(); fan();'>
按照 Utkanos 的建议使用。
If you use jQuery, you can also stick a script in the head containing:
如果您使用 jQuery,您还可以在头部粘贴一个包含以下内容的脚本:
$(function(){
...
});
The jQuery function actually fires earlier, as is explained here.
jQuery的功能其实更早触发,如解释在这里。