前言

  • jQuery v3.5.1

jQuery 查找元素

比如查找某个input元素$("input[name='email']")

示例:

<html>
<header>
<script crossorigin="anonymous" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" src="https://lib.baomitu/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
  $("#form1").submit(function(){
    alert($("input[name='email']").val());
	return false;
  });
});
</script>
</header>

<body>
  <form id="form1" action="#">
  	<span>邮箱:</span><input type="text" name="email" value="1@1" /><br/>
	<input type="submit" />
  </form>
</body>
</html>

jQuery 判断元素是否存在

使用 jQuery 查找元素时,如果该元素不存在,则会影响后面的代码执行。因此需要判断元素是否存在。

jQuery 查找的元素不存在时,依然会返回对象。

if($("input[name='email']")) {
    //永远执行,不管元素是否存在
}

可以通过 jQuery 的 length 属性判断元素是否存在。

if($("input[name='email']").length > 0) {
    // 存在
}

示例:

<html>
<header>
<script crossorigin="anonymous" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" src="https://lib.baomitu/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
  $("#form1").submit(function(){
    if ($("input[name='email']")) {
      alert("jQuery 判断元素是否存在方式1:元素存在"); /* 不管元素是否存在,永远执行这里 */
    } else {
      alert("jQuery 判断元素是否存在方式1:元素不存在");
	}

	if ($("input[name='email']").length > 0) {
      alert("jQuery 判断元素是否存在方式2:元素存在"); /* 元素存在时执行这里 */
    } else {
      alert("jQuery 判断元素是否存在方式2:元素不存在"); /* 元素不存在时执行这里 */
	}
	return false;
  });
});
</script>
</header>

<body>
  <form id="form1" action="#">
	<input type="submit" />
  </form>
</body>
</html>

参考

https://www.w3school/jquery/index.asp
https://www.runoob/w3cnote/jquery-check-id-is-exists.html

更多推荐

jQuery 判断元素是否存在