利用:header匹配所有标题做目录

1、问题背景

     查找到h1-h6,并遍历它们,打印出内容

2、实现源码

[html] view plain copy
 
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="utf-8" />  
  5.         <title>查找标题</title>  
  6.         <script type="text/javascript" src="js/jquery-2.2.3.js" ></script>  
  7.         <script>  
  8.             $(function(){  
  9.                 //查找h1-h6  
  10.                 $(":header").each(function(){  
  11.                     $(this).click(function(event){  
  12.                         console.info(event.target.innerText);  
  13.                         console.log(event.currentTarget.innerHTML);  
  14.                     });  
  15.                 });  
  16.             });  
  17.         </script>  
  18.     </head>  
  19.     <body>  
  20.         <h1>Hello H1</h1>  
  21.         <h2>Hello H2</h2>  
  22.         <h3>Hello H3</h3>  
  23.         <h4>Hello H4</h4>  
  24.         <h5>Hello H5</h5>  
  25.         <h6>Hello H6</h6>  
  26.     </body>  
  27. </html>  

3、实现结果

4、结果说明

(1)$(":header")

        选择所有标题元素

(2)each函数

        遍历h1-h6

(3)event.target.innerText

        获取点击元素内容内容

(4)event.currentTarget.innerHTML

        获取点击元素内容内容

版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:https://www.cnblogs.com/jinhengyu/p/7542387.html