zoukankan      html  css  js  c++  java
  • 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内的内容,使用上面两种方法即可获取你想要的内容。

  • 相关阅读:
    140704
    140703
    140702
    堆排序
    并查集
    140701
    这年暑假集训-140630
    vim for python
    hihocode 第九十二周 数论一·Miller-Rabin质数测试
    hdu 3157 Crazy Circuits 有源汇和下界的最小费用流
  • 原文地址:https://www.cnblogs.com/pukua/p/14813241.html
Copyright © 2011-2022 走看看