首页 > 解决方案 > jQuery .remove() 对 null 元素有什么作用?

问题描述

$('#something').find('#something').remove()的代码中有。

我只是想知道如果find()返回 null 会发生什么。我实际尝试过,它没有显示任何错误并且工作正常。那么,如果我们对 null 元素调用 remove 会发生什么?

这是一个基本问题,但在文档中找不到。

标签: jquery

解决方案


我已经检查过了,如果 find() 没有得到结果数据,那么如果你在 console.log 中检查它就不会发生任何事情,它会重新调整一个具有长度的对象

如果你这样做console.log($("ul").find("span"));,它将返回具有长度的对象

w.fn.init(2) [span, span, prevObject: w.fn.init(1)]
0: span
1: span
length: 2
prevObject: w.fn.init [ul, prevObject: w.fn.init(1)]
__proto__: Object(0)

如果console.log($("ul").find("div"));在这种情况下这样做,后代子 div 不存在,因此它将返回长度为 0 的对象

w.fn.init [prevObject: w.fn.init(1)]
length: 0
prevObject: w.fn.init [ul, prevObject: w.fn.init(1)]
__proto__: Object(0)

你可以检查这个例子

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("ul").find("li").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>

<body class="ancestors">body (great-grandparent)
  <div style="width:500px;">div (grandparent)
    <ul>ul (direct parent)  
      <li>li (child)
        <span>span (grandchild)</span>
      </li>
    </ul>   
  </div>
</body>

</html>

您可以了解更多有关查找的信息

https://api.jquery.com/find/

我希望它会帮助你。


推荐阅读