简体   繁体   English

为什么JavaScript函数的参数返回“未定义”?

[英]Why does a parameter of a JavaScript function return 'undefined'?

I'm trying to write a simple a JS function which randomly rotates the background-image of a CSS block per 1 second. 我正在尝试编写一个简单的JS函数,该函数每1秒随机旋转CSS块的背景图像。 I want to add the name of the block and the number of images from paramaters, so the function can be as flexible as possible and a I can call multiple instances of it on one page. 我想添加块的名称和来自参数的图像数,因此该功能可以尽可能灵活,并且我可以在一页上调用它的多个实例。 The problem is that I get ' nameofparamter undefined' Error. 问题是我收到“ nameofparamter undefined”错误。

Here's the script with the HTML 这是带有HTML的脚本

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="hu-HU" lang="hu">
<head>
<meta name="http-equiv" content="text/html; charset="utf-8"">
<meta name="description" content="leiras"><meta name="keywords" content="kulcsszavak"/>
<style type="text/css"> 
div#mycontainer{
background-image: url(images/bg_image1.jpg);
width: 800px;
height: 600px; 
}
</style>
<script type="text/javascript" charset="utf-8">
function changeBgImage(num, el){
    var imageNum = num;
    var randomImageNum = Math.ceil(Math.random()*imageNum);

    if(el!=='null'){
        el.style.backgroundImage='url(images/bg_image'+randomImageNum+'.jpg';
            var timer = setTimeout("changeBgImage(num, el)", 1000);
    }
}

</script>  
</head>
<title>Dynamic Backgroundimage changer</title>
<body onload="changeBgImage(4, document.getElementById('mycontainer'));">
<div id="mycontainer">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut felis purus, dictum quis pellentesque ut, venenatis et tellus. Phasellus gravida cursus urna, quis hendrerit risus rutrum vel. Suspendisse dictum lobortis molestie. Sed quis lacus nec ante dignissim sollicitudin. Curabitur tristique facilisis turpis.
</div>  
</body>
</html>

I don't really understand 'cause there's the iterated value of both parameters in the body's onload event handler where I call the function? 我不太了解,因为在调用函数的主体的onload事件处理程序中,两个参数都有迭代值吗? So why undefined ? 那么为什么未定义呢? Your help is very much welcomed! 非常欢迎您的帮助! :) :)

There's a bunch of things that ain't right about your code. 关于您的代码,有很多事情是不对的。 For one thing, your null check only checks that the variable does not have a string value that is exactly 'null' . 一方面,您的null检查仅检查该变量没有确切地为'null'的字符串值。 Where you're setting backgroundImage property, the string you're assigning has unmatching parentheses. 在设置backgroundImage属性的地方,要分配的字符串具有不匹配的括号。

But most of all, setTimeout executes on the window context, where your variables are not available (nor should you want them to be). 但最重要的是, setTimeout在不可用变量(也不希望它们可用)的window上下文中执行。 Instead, change your call to 相反,将您的呼叫更改为

setTimeout(function() { changeBgImage(num, el) }, 1000);

So a complete fix would be 所以一个完整的解决办法是

if(el){
    el.style.backgroundImage='url(images/bg_image'+randomImageNum+'.jpg);';
    var timer = setTimeout(function() { changeBgImage(num, el) }, 1000);
}

change 更改

setTimeout("changeBgImage(num, el)", 1000);

to

setTimeout(function() { changeBgImage(num, el) }, 1000);

This is a guess but firstly because your invoking the function in quotes it invokes it in the global context, and num and el are not defined in global context, but within your function. 这是一个猜测,但首先是因为您在引号中调用函数会在全局上下文中调用它,而numel不是在全局上下文中定义的,而是在函数内部定义的。 Try using a function literal eg 尝试使用函数文字,例如

setTimeout( function() { changeBgImage( num, el ) }, 1000 );

PS, you should be using != null not the string null. PS,您应该使用!= null而不是字符串null。

When you call a function with setTimeout you cannot pass objects as parameters. 使用setTimeout调用函数时,无法将对象作为参数传递。 So I recommend you to approach the problem in other way. 因此,我建议您以其他方式解决该问题。 You can have shared variables to pass the arguments. 您可以具有共享变量来传递参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM