Loading

JQuery 只获取当前元素的内容,不获取子级元素的内容

代码展示

<html>
<head>
<style>
body{
background-color:#f9f3e1;
}
</style>
</head>
<body>
<div>
    <p id="content">哈哈哈<span>你看起来很好吃</span>嘿嘿嘿</p>
	<br/>
	<p id="printfcontent1"></p>
	<p id="printfcontent2"></p>
</div>

<script src="jquery-3.4.1.min.js"></script>
<script>
//方法一
func1();
function func1(){
var obj = $("div").children("p").clone();
obj.find(':nth-child(n)').remove();
$("#printfcontent1").html("方法一获取的内容:"+obj.html());
}

//方法二
func2();
function func2(){
var str = $('div #content').contents().filter(function (index, content) {
    return content.nodeType === 3;
}).text();
$("#printfcontent2").html("方法二获取的内容:"+str);
}
</script>
</body>
</html>

所需要jquery文件:jquery-3.4.1.min.js

实现效果

如上面代码和图片所示,我想要获取P标签中为“哈哈哈嘿嘿嘿”的内容,不想获取p标签中的span以及span内的内容,使用上面两种方法即可获取你想要的内容。

posted @ 2021-05-26 16:41  河耶悦悦  阅读(654)  评论(0编辑  收藏  举报