专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 jQuery判断元素是否存在的方法

jQuery判断元素是否存在的方法

更新时间:2021-09-01 11:29:48 来源:赢咖4 浏览2121次

jQuery中,您可以使用.length属性来检查元素是否存在。如果元素存在,则length属性将返回匹配元素的总数。

例如,

f($('#div1').length){
	alert("Div1 exists");
}else{
	alert("Div1 does not exists");
}

检查id为“div1”的元素是否存在。

jQuery长度示例

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<h1>jQuery check if an element exists</h1>
<script type="text/javascript">
  $(document).ready(function(){
    $("#buttonDiv1").click(function () {		
	if($('#div1').length){
		alert("Div1 exists");
	}else{
		alert("Div1 does not exists");
	}			
    });
    $("#buttonDiv2").click(function () {		
	if($('#div2').length){
		alert("Div2 exists");
	}else{
		alert("Div2 does not exists");
	}			
    });	
  });
</script>
</head><body>
<div id="div1">
	<b>This is DIV element which has an ide of "div1"</b>
</div>
<br/>
<br/>
<br/>
<input type='button' value='div1 exists?' id='buttonDiv1'>
<input type='button' value='div2 exists?' id='buttonDiv2'>
</body>
</html>

以上就是赢咖4小编介绍的"jQuery判断元素是否存在的方法",希望对大家有帮助,想了解更多可查看 jQuery教程。赢咖4Java赢咖4在线学习教程,针对没有任何Java基础的读者学习,让你从入门到精通,主要介绍了一些Java基础的核心知识,让同学们更好更方便的学习和了解Java编程,感兴趣的同学可以关注一下。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>