一、jquery判断标签内容是否为空

  

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

  1.当a标签里无内容时不显示当前a标签;

  2.当a标签里有内容时显示当前a标签;

 

二、设计源码

 

   1.html:div里放置几个a标签,任选几个输入内容,其余为空;

1 <div id="Div">
2     <a href="javascript:void(0);">1</a>
3     <a href="javascript:void(0);"></a>
4     <a href="javascript:void(0);">2</a>
5     <a href="javascript:void(0);">3</a>
6     <a href="javascript:void(0);"></a>
7     <a href="javascript:void(0);">4</a>
8 </div>

 

   2.css:给a标签定个样式;

 1 <style type="text/css">
 2   a{ text-decoration:none;}
 3   #Div a{
 4       display:inline-block;
 5       vertical-align:middle;
 6       width:30px;
 7       height:30px;
 8       line-height:30px;
 9       text-align:center;
10       background-color:black;
11       color:white;
12   }
13 </style>

 

        如图所示:

           jquery判断标签内容是否为空 随笔 第1张


   3.jquery判断;

 1 <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
 2 <script type="text/javascript">
 3   $(document).ready(function(){
 4       $("#Div a").each(function(){
 5           var ainH = $(this).html();
 6           if(ainH == null || ainH.length == 0){
 7               $(this).hide();
 8           } else{
 9               $(this).show();
10           }
11       });
12   });
13 </script>

 

 

三、最终实现

 

jquery判断标签内容是否为空 随笔 第2张

 

四、举一反三

 

  由此,可进行判断指定文字显示a标签,否则隐藏。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
 7 <script type="text/javascript">
 8     $(document).ready(function(){
 9         $("#Div a").each(function(){
10             var ainH = $(this).html();
11             if(ainH == "show"){  //指定内容只是为show则显示,否则隐藏
12                 $(this).show();
13             } else{
14                 $(this).hide();
15             }
16         });
17     });
18 </script>
19 <style type="text/css">
20   a{ text-decoration:none;}
21   #Div a{
22       display:inline-block;
23       vertical-align:middle;
24       padding:0 10px;
25       height:30px;
26       line-height:30px;
27       text-align:center;
28       background-color:black;
29       color:white;
30   }
31 </style>
32 </head>
33 <body>
34 <div id="Div">
35     <a href="javascript:void(0);">1</a>
36     <a href="javascript:void(0);">show</a>
37     <a href="javascript:void(0);">2</a>
38     <a href="javascript:void(0);">3</a>
39     <a href="javascript:void(0);">a-show-hide</a>
40     <a href="javascript:void(0);">4</a>
41 </div>
42 </body>
43 </html>

 

    如图所示:

    jquery判断标签内容是否为空 随笔 第3张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄