jquery - jQuery .remove() 对 null 元素有什么作用?
问题描述
我$('#something').find('#something').remove()
的代码中有。
我只是想知道如果find()
返回 null 会发生什么。我实际尝试过,它没有显示任何错误并且工作正常。那么,如果我们对 null 元素调用 remove 会发生什么?
这是一个基本问题,但在文档中找不到。
解决方案
我已经检查过了,如果 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>
您可以了解更多有关查找的信息
我希望它会帮助你。
推荐阅读
- pandoc - 生成 HTML 时在 Pandoc 中按年份组织引用
- debezium - 以 ISO-8601 格式返回日期 - Debezium/Postgres 插件
- apache-kafka - 使用 kafka 进行 CQRS
- reactjs - 使用 jest 模拟 react-router-dom 钩子不起作用
- cmake - 如何指定 target_link_libraries 使用的库的 cmake 路径
- java - Java builder 类泛型层次结构:如何使 build() 返回正确的方法
- python - 如何修复打印语句,使其位于一行而不是两行?
- python - 在 Django 中的不同视图之间传递数据
- python - 如何仅选择具有唯一(不重复)字段的行?
- .net - AcceptTcpClientAsync 返回,但没有可用数据