0

Suppose I have created one jQuery function to check if elements exist or not like:

jQuery.fn.exists = function () { 
    return this.length > 0; 
}

Then I call:

if ($("#MyDiv").exists() == false)
   alert('not exist');
else
   alert('exist');

If I call jQuery function above it works. But can't we call the jquery function like this way exists('#MyDiv') ? If I try to call this way then I am not getting result...why?

4

4 回答 4

2

ARRG,请不要使用这个无用的exist功能!

它可以简单地使用:

if ($('#MyDiv').length)
    // Exist
else
    // Doesn't exist.

不需要插件,每个人都知道这段代码的作用,不要使用exist.

于 2012-06-19T18:40:09.593 回答
1

尝试如下,

$.exists = function (selector) {
    return $(selector).length > 0;
}

并用作,

$.exists('#test') 

演示:http: //jsfiddle.net/skram/hgaPt/1/

请在更大的范围内使用它,将它用于现有的简单事物只是一种矫枉过正。

于 2012-06-19T18:40:33.790 回答
0

$.fn等于$.prototype,因此间接使用$.fn您将函数挂钩到 jQuery 对象原型,因此需要将选择器传递给 jQuery 对象而不是链式函数名称。

于 2012-06-19T18:47:46.973 回答
0
exists('#MyDiv')

这不起作用,因为您没有创建一个名为exists. 您创建了一个名为jQuery.fn.exists(jQuery.fnprototypejQuery 对象的函数)。

为了exists('#MyDiv')工作,您需要创建一个名为exists.

function exists(sel){
    return $(sel).length;
}
于 2012-06-19T18:46:22.343 回答