jQuery判断DOM节点是否存在页面中
1、首先在jquery原型上添加一个exist方法;
2、然后在方法内判断当前对象length属性是否大于0,大于就存在;
3、最后通过$('#id').exist()进行调用即可。
添加原型:
(function($) {
$.fn.exist = function(){
if($(this).length>=1){
return true;
}
return false;
};
})(jQuery);
使用方法:
假如页面有如下DOM节点
<div id="a">这里是id=a节点</div> <div>这里是DIV节点</div> <div>这里是DIV节点</div> <span>这里是span节点</span>
判断:
alert($('#aaa').exist()); // false
alert($('#a').exist()); // true
alert($('div').exist()); // true
alert($('p').exist()); // false

