jQuery determining if element exists on page
How can I determine if an element exists on a page... for instance...
$('select[name="modifier_option"]')
If that select box exists on the screen I need to validate it's value on the page to ensure it's value is > 0, but if it doesn't exist I don't need to worry about it.
if( $('select[name="modifier_option"]').length )
{
// it exists
}
从这里复制/粘贴:是否有一个jQuery的“存在”功能?
jQuery.fn.exists = function(){return jQuery(this).length>0;}
if ($(selector).exists()) {
// Do something
}
I answered this same question with the following plugin here . Please visit answer for full details on creating of plugin.
The following plugin would allow you to use a callback feature (staying inline with jQuery style markup) if the element exist. So for your example, you might do something like:
$('select[name="modifier_option"]').exist(function() {
if ($(this).val() > 0) {
/* DO WORK */
}
else {
/* is not greater than 0
DO OTHER WORK */
}
})
Plugin
(function($) {
if (!$.exist) {
$.extend({
exist: function() {
var ele, cbmExist, cbmNotExist;
if (arguments.length) {
for (x in arguments) {
switch (typeof arguments[x]) {
case 'function':
if (typeof cbmExist == "undefined") cbmExist = arguments[x];
else cbmNotExist = arguments[x];
break;
case 'object':
if (arguments[x] instanceof jQuery) ele = arguments[x];
else {
var obj = arguments[x];
for (y in obj) {
if (typeof obj[y] == 'function') {
if (typeof cbmExist == "undefined") cbmExist = obj[y];
else cbmNotExist = obj[y];
}
if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
if (typeof obj[y] == 'string') ele = $(obj[y]);
}
}
break;
case 'string':
ele = $(arguments[x]);
break;
}
}
}
if (typeof cbmExist == 'function') { // has at least one Callback Method
var exist = ele.length > 0 ? true : false; // strict setting of boolean
if (exist) { // Elements do exist
return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
}
else if (typeof cbmNotExist == 'function') {
cbmNotExist.apply(ele, [exist, ele]);
return ele;
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
}
else { // has NO callback method, thus return if exist or not based on element existant length
if (ele.length <= 1) return ele.length > 0 ? true : false; // strict return of boolean
else return ele.length; // return actual length for how many of this element exist
}
return false; // only hits if something errored!
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
jsFiddle
链接地址: http://www.djcxy.com/p/83852.html上一篇: 如何在jQuery中检查空对象
下一篇: jQuery确定页面上是否存在元素