jQuery如何使用contents()?用法示例

2021年3月27日15:37:39 发表评论 1,037 次浏览

contents()是jQuery中的内置方法, 它返回所有直接子级, 包括所选元素的文本和注释节点。

语法如下:

$(selector).contents()

参数:它不接受任何参数。

返回值:它返回所选元素的所有直接子元素。

jQuery代码显示此方法的工作方式:

代码1:

< html >
  
< head >
     < script src="https://ajax.googleapis.com/ajax/libs/
                jquery/3.3.1/jquery.min.js"></ script >
     < script >
         $(document).ready(function() {
             <!-- jQuery code to perform this method -->
             $("button").click(function() {
                 $("div").contents().filter("p").wrap("< b />");
             });
         });
     </ script >
     < style >
         #p1 {
             width: 420px;
             padding: 50px;
             display: block;
             border: 2px solid green;
             font-size: 30px;
         }
     </ style >
</ head >
  
< body >
     < div >
         <!-- This paragraph will get bold after click on
               the button -->
         < p id = "p1" >Welcome to lsbin !!!</ p >
     </ div >
     <!-- click on this button -->
     < button >Click Me!</ button >
     < br >
</ body >
  
</ html >

输出如下:

在点击"点击我!"之前按钮-

jQuery如何使用contents()?用法示例1

点击"点击我!"后按钮-

jQuery如何使用contents()?用法示例2

代码2:

在下面的代码中, 无需单击任何按钮。

< html >
  
< head >
     < script src = "https://code.jquery.com/jquery-1.10.2.js" ></ script >
     < style >
         #p1 {
             display: block;
             width: 400px;
             padding: 30px;
             border: 2px solid green;
             font-size: 30px;
         }
     </ style >
</ head >
  
< body >
     <!-- This paragraph will get bold -->
     < p id = "p1" >Welcome to lsbin !</ p >
     < script >
         $("p")
             .contents()
             .filter(function() {
                 return this.nodeType !== 1;
             })
             .wrap("< b ></ b >");
     </ script >
</ body >
  
</ html >

输出如下:

jQuery如何使用contents()?用法示例3

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: