使用过JQ的朋友都知道,jQuery有一个专门的遍历class方法hasClass(),但是没有hasId()方法,那么要如何才能获得某个id是否存在呢?在JavaScript中我们可以直接使用document.getElementById(“id”),即可判断。
对于jQurey来说,看到原生JavaScript的方法,我们肯定会想到$(‘#id’),但是在输出的时候,不论页面上有没有这个id都显示object object,因此这种方法是不可取的,但是可以使用以下方法
if($("#id").length>0){}else{}
//或者
if($("#id")[0]){} else {}
因为jQurey中可以直接使用原生JavaScript,因此我们也可以直接使用原生JavaScript的方法进行判断。
除了上面的方法还有以下几个方法
1、根据父节点查找子节点
jQuery之children()返回匹配对象的字节点
children() 返回匹配对象的子介点
one
two
jQuery代码及功能:
function jq(){
alert($(“#ch”).children().html());
}
$(“#ch”).children()得到对象[ two ].所以.html()的结果是”two”
2、根据子节点查找父节点
two
three
three
jQuery代码及功能
Jquery.ready ({
alert($(“#ch”).children(“#sp”).html());
});
$(“#ch”).children()得到对象[twothree ].
$(“#ch”).children(“#sp”)过滤得到[three ]