JavaScript 两个 onload 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15684168/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:41:43  来源:igfitidea点击:

JavaScript two onload functions

javascripthtmlfunctiondomonload

提问by SineLaboreNihil

I am quite new to JavaScript programming and I'm trying to create some scripts that would save me time in maintaining one of my websites.

我对 JavaScript 编程很陌生,我正在尝试创建一些脚本,以节省维护我的网站之一的时间。

Now I have two functions in the same script that I'm calling from the head of my document and I'm trying to get them both to load at the same time with an onload event handler. I am doing that with window.onload command in my script (I want to make my script as unobtrusive as possible so I'm just calling the script in the header). The problem is that only the first function loads and the second one doesn't. Can both functions be called with:

现在我在同一个脚本中有两个函数,我从文档的头部调用它们,我试图让它们同时加载一个 onload 事件处理程序。我在我的脚本中使用 window.onload 命令执行此操作(我想让我的脚本尽可能不引人注目,所以我只是在标题中调用脚本)。问题是只有第一个函数加载,第二个没有。这两个函数都可以通过以下方式调用:

window.onload=function(){
function1();
function2();
}

or is there a different code I need to use to accomplish this?

还是我需要使用不同的代码来完成此操作?

I would really appreciate it if you could make your explanations as simple as possible as I am very new to JavaScript and programming in general.

如果您能让您的解释尽可能简单,我将不胜感激,因为我对 JavaScript 和编程非常陌生。

P.S. If more than one function can't be loaded with onload, could you please explain to me why this is the case so I know in the future.

PS 如果 onload 无法加载多个函数,请您向我解释为什么会这样,以便我将来知道。

Ok, I see by the answers that my question probably left too much for assumption so here is the entire code of the functions I am trying to call (this is the script I am calling in the head of my html document):

好的,我从答案中看到,我的问题可能没有太多假设,所以这里是我试图调用的函数的完整代码(这是我在 html 文档的头部调用的脚本):

I was trying to avoid putting the code here because my variables are written in Serbian language (as I am from Serbia), but I hope that you will still be able to look through it without much confusion.

我试图避免将代码放在这里,因为我的变量是用塞尔维亚语编写的(因为我来自塞尔维亚),但我希望您仍然能够在没有太多困惑的情况下浏览它。

In the code below I am calling at the bottom of the script two functions (lista() and ostale()) and the moveover() function is just a helper function called by the lista() function. In essence the first one (lista()) lists through all elements of div "boje" (in English translated to "colors") and depending on the color the user hovers their mouse over, the background image changes. It also adds a few attributes to those image elements that the user is supposed to hover over. The second one (ostale() (Translated to English "others") is supposed to only add attributes to the rest of the color images that are not supposed to do anything if the user hovers over them. But when I open the page in localhost it doesn't show in Firefox's inspect element that any attributes have been added to the images within the div "ostale".

在下面的代码中,我在脚本底部调用了两个函数(lista() 和 ostale()),而 moveover() 函数只是由 lista() 函数调用的辅助函数。本质上,第一个 (lista()) 列出了 div“boje”(英文翻译为“colors”)的所有元素,并且根据用户将鼠标悬停在其上方的颜色,背景图像会发生变化。它还为用户应该悬停的那些图像元素添加了一些属性。第二个(ostale()(翻译成英文“others”)应该只向其余的彩色图像添加属性,如果用户将鼠标悬停在它们上面则不应该做任何事情。但是当我在本地主机中打开页面时它不会显示在 Firefox 中”

function lista()
{
var boje = document.getElementById('boje');
var broj = boje.childNodes.length;
for(i=1; i<broj; i++)
{
    var stavka = boje.childNodes.item(i);
    stavka.setAttribute("id", i);
    stavka.setAttribute("onmouseover", "moveover(src)");
    stavka.setAttribute("alt", "Boja");
    stavka.setAttribute("class", "boja");
    stavka.hspace="2";
    stavka.height="23";
}
}

function moveover(adresaBoje)
{
var izvor = adresaBoje;
var slika = izvor.slice(0, izvor.length-4);
var pocetak = "url(";
var ekstenzija = ".jpg)";
var novaSlika = pocetak.concat(slika, ekstenzija);
document.getElementById('slika').style.backgroundImage=novaSlika;
}

function ostalo(){
var ostaleboje = document.getElementById('ostale');
var ostalebroj = ostaleboje.childNodes.length;
for(n=1; n<ostalebroj; n++)
{
    var ostalestavka = ostaleboje.childNodes.item(n);
    ostalestavka.setAttribute("alt", "Boja");
    ostalestavka.hspace="2";
    ostalestavka.height="23";
}
}

window.onload=function(){
try
{
lista();
ostalo();
}
catch(err)
{
alert(err);
}
}

After I try to load the page it alerts me with an error: "TypeError: stavka.setAttribute is not a function".

在我尝试加载页面后,它提醒我一个错误:“TypeError:stavka.setAttribute 不是函数”。

This is the html document I am trying to manipulate:

这是我试图操作的 html 文档:

<div id="slika" style="background-image: url(images/nova_brilliant/1.jpg)">
</div>

<div id="tekst">

<h1>Nova Brilliant</h1>

<div id="sadrzaj">
<p>Pre&#273;ite mi&#353;em preko &#382;eljene boje da biste videli kako izgleda ova kuhinja u toj boji:</p>
<div id="boje">
<img src="images/nova_brilliant/1.gif"><img src="images/nova_brilliant/2.gif"><img src="images/nova_brilliant/3.gif">
</div>
<p>Ostale dostupne boje:</p>
<div id="ostale">
<img src="images/nova_brilliant/4.gif"><img src="images/nova_brilliant/5.gif"><img src="images/nova_brilliant/6.gif">
</div>
</div>

</div>

采纳答案by aIKid

Yes you can. However, if the first goes wrong, the second won't fire.

是的你可以。但是,如果第一个出错,第二个就不会触发。

Use this to catch errors:

使用它来捕获错误:

try { //try executing the functions
  function1();
  function2();
}
catch(error) { // If there's an error
  alert(error); // alert the error.
}

It is a good practice to put tryand catchwhen experimenting with javascript.

这是一个很好的做法把trycatch用JavaScript实验时。

Edited: Sorry i confused childNodes[] with childNodes.item().

编辑:抱歉,我将 childNodes[] 与 childNodes.item() 混淆了。

By the way, I tried something like this, and it works just fine:

顺便说一下,我尝试过这样的事情,它工作得很好:

<head>
<script>

window.onload = function() {
div = document.getElementById("someDiv");
length = div.childNodes.length;
    first();
    second();
}
function first() {
    for(var i=0;i<length;i++)   {
        var set = div.childNodes.item(i);
        set.setAttribute("name", "span " + (i+1));
    }     
}
function second() {
    for(var i=0;i<length;i++)   {
        name = div.childNodes[i].getAttribute("name");
        console.log(name);
    }
}
</script>
</head>
<body>
<div id='someDiv'><span id='span1'></span><span id='span2'></span></div>
</body>

UPDATE: I found the error:Actually there's nothing wrong with your code. It works just fine, however, the last item of boje is empty space, which means, a text node. That's why the error keeps showing up. Change for(i=1; i<broj; i++)with for(i=1; i<broj-1; i++)and everything should be good.

更新:我发现错误:实际上您的代码没有任何问题。它工作得很好,但是, boje 的最后一项是空白区域,这意味着,一个文本节点。这就是错误不断出现的原因。改变for(i=1; i<broj; i++)for(i=1; i<broj-1; i++)一切都应该是好的。

回答by Kunle

I ran into the same problem. I came across a couple of help but this one was easy to understand and it worked for me:

我遇到了同样的问题。我遇到了一些帮助,但这个很容易理解并且对我有用:

window.addEventListener("load", func1); window.addEventListener("load", func2);

just like @Quentin You can read more about it here

就像@Quentin 你可以在这里阅读更多相关信息

回答by Quentin

Can both functions be called with

两个函数都可以用

Yes. If you add event handlers by assigning to DOM properties, then you can only assign a single function to each but that function can call other functions.

是的。如果您通过分配给 DOM 属性来添加事件处理程序,那么您只能为每个属性分配一个函数,但该函数可以调用其他函数。

However, if you do that and the first function throws an error then the second function won't fire at all. It will also discard the context and arguments, as they won't be passed to the called functions.

但是,如果您这样做并且第一个函数抛出错误,则第二个函数根本不会触发。它还将丢弃上下文和参数,因为它们不会传递给被调用的函数。

You could work around those problems like so:

您可以像这样解决这些问题:

window.onload=function(){
  try {
    function1.apply(this, arguments);
  } catch (e) { }
  try {
    function2.apply(this, arguments);
  } catch (e) { }
}

or is there a different code I need to use to accomplish this?

还是我需要使用不同的代码来完成此操作?

You should use addEventListenerinstead. That avoids the need to fiddle with apply, and protects you from errors being thrown. See the MDN events documentationfor more details.

你应该addEventListener改用。这避免了摆弄 apply 的需要,并保护您免受抛出的错误。有关更多详细信息,请参阅MDN 事件文档

window.addEventListener('load', function1);
window.addEventListener('load', function2);