如何确定页面上是否存在元素...例如......
$('select[name="modifier_option"]')
如果屏幕上存在该选择框,我需要在页面上验证它的值,以确保其值为> 0,但如果它不存在我不需要担心它。
答案 0 :(得分:19)
if( $('select[name="modifier_option"]').length )
{
// it exists
}
答案 1 :(得分:4)
从此处复制/粘贴:Is there an "exists" function for jQuery?
jQuery.fn.exists = function(){return jQuery(this).length>0;}
if ($(selector).exists()) {
// Do something
}
答案 2 :(得分:0)
我使用以下插件here回答了同样的问题。有关创建插件的详细信息,请访问答案。
如果元素存在,以下插件将允许您使用回调功能(保持与jQuery样式标记内联)。因此,对于您的示例,您可能会执行以下操作:
$('select[name="modifier_option"]').exist(function() {
if ($(this).val() > 0) {
/* DO WORK */
}
else {
/* is not greater than 0
DO OTHER WORK */
}
})
(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);