简体   繁体   English

Javascript:在另一个函数内部调用函数不起作用?

[英]Javascript: calling function inside another function not working?

So inside my <script> tags, I have these functions. 因此,在我的<script>标记中,我具有这些功能。

$.fn.getRandom = function(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

function placeRandom() {
    alert(getRandom(1,7));
}

and I call the placeRandom() function like so 我像这样调用placeRandom()函数

$(document).ready(function() {
    placeRandom();
});

when I do this, it gives me an 当我这样做时,它给了我一个

Object expected

error and refers to the line where I wrote 错误,指的是我写的那一行

alert(getRandom(1.7));

Now, my main question is if there is anything wrong with the code which I am showing you, or does it look correct? 现在,我的主要问题是我显示给您的代码是否有问题,或者看起来正确吗? Because if it looks correct then I think i'm going to have to run through the rest of my entire code and look for maybe a open bracket which isn't closed because that might be the problem. 因为如果看起来正确,那么我认为我将不得不遍历整个代码的其余部分,并寻找一个可能没有解决的可能没有被关闭的方括号。 So yea, is there any problem with my placeRandom() or getRandom() function or is the error occuring because of another reason other than these functions? 所以,是的,我的placeRandom()或getRandom()函数是否存在任何问题,或者是否由于这些函数以外的其他原因而发生了错误?

The problem is were you are defining the getRandom function. 问题是您正在定义getRandom函数。 You are putting it in the jQuery.fn namespace. 您将其放在jQuery.fn命名空间中。 If you organize your code like the following it should work much better. 如果按照以下方式组织代码,则效果会更好。

var getRandom = function(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

var placeRandom = function() {
    alert(getRandom(1,7));
}

$(document).ready(function() {
    placeRandom();
});

Additional Info: jQuery.fn is actually a prototype but is commonly referred to as a namespace in this specific context. 附加信息: jQuery.fn实际上是一个原型,但在此特定上下文中通常称为命名空间。

You are binding getRandom to the jQuery namespace, you will only be able to access it through a jQuery object instance or via $.fn.getRandom() 您将getRandom绑定到jQuery命名空间,您将只能通过jQuery对象实例或通过$.fn.getRandom()访问它。

So unless you want to be able to call it like $(selector).getRandom() , just declare it as a standard function. 因此,除非您希望能够像$(selector).getRandom()那样调用它,否则只需将其声明为标准函数即可。

you are binding getRandom to the $ namespace (jQuery). 您将getRandom绑定到$名称空间(jQuery)。 so you have to call it $.fn.getRandom(1,7) or define the function the following: 因此,您必须将其称为$.fn.getRandom(1,7)或定义以下函数:

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

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

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