0

所以在我的<script>标签中,我有这些功能。

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

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

我这样调用placeRandom()函数

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

当我这样做时,它给了我一个

Object expected

错误,指的是我写的那行

alert(getRandom(1.7));

现在,我的主要问题是我向您展示的代码是否有任何问题,或者看起来是否正确?因为如果它看起来正确,那么我认为我将不得不遍历我的整个代码的其余部分,并寻找一个可能没有关闭的开放括号,因为这可能是问题所在。所以,是的,我的 placeRandom() 或 getRandom() 函数是否有任何问题,或者是否由于这些函数以外的其他原因而发生错误?

4

3 回答 3

2

The problem is were you are defining the getRandom function. You are putting it in the jQuery.fn namespace. 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.

于 2013-10-16T14:52:56.823 回答
1

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()

So unless you want to be able to call it like $(selector).getRandom(), just declare it as a standard function.

于 2013-10-16T14:52:50.070 回答
1

您正在绑定getRandom到 $ 命名空间(jQuery)。所以你必须调用它$.fn.getRandom(1,7)或定义以下函数:

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}
于 2013-10-16T14:54:19.357 回答