2014-09-06 69 views
0
<ul> 
    <li><a href="">not here</a></li> 
    <li><a href="">append some text only here</a> 
    <ul> 
    <li><a href="">not here</a></li> 
    <li><a href="">not here</a></li> 
    <li><a href="">not here</a></li> 
    </ul> 
    </li> 
    <li><a href=""></a>not here</li> 
</ul> 

我想追加一些文本只有当li标签有一个孩子ul标签。jquery append methos

+0

如果你要添加的文字吗? – 2014-09-06 12:53:13

+0

在你的例子中没有'li'有一个'ul'作为孩子 – steo 2014-09-06 12:53:31

+0

@steo - 实际上,其中一个是! – adeneo 2014-09-06 12:54:39

回答

0

它看起来像你想要把文本中<a> ,所以一旦你找到了<li>个S,寻找孩子这是<a>

$('li:has(ul)').children('a').text('foobar'); 
+0

谢谢。这对我有用。 – user2333124 2014-09-06 13:02:58

0
$('li a').text(function(i,v){ 
    if($(this).parent().children('ul').length){ 
    return v == 'append some text only here'; 
    } 
}); 

或者使用:has

$('li:has(ul)').children('a').text('append some text only here'); 
0
<!DOCTYPE html> 

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta charset="utf-8" /> 
    <title></title> 
    <script src="https://code.jquery.com/jquery-2.1.1.js"> 
    </script> 
</head> 
<body> 
    <ul> 
     <li><a href="">not here</a></li> 
     <li> 
      <a href="">append some text only here</a> 
      <ul> 
       <li><a href="">not here</a></li> 
       <li><a href="">not here</a></li> 
       <li><a href="">not here</a></li> 
      </ul> 
     </li> 
     <li><a href=""></a>not here</li> 
    </ul> 
    <script> 
     $(document).ready(function() { 
      $('li').has('ul').each(function (index) { 
       $(this).find('a').html("test"); 
      }); 
     }); 
    </script> 
</body> 
</html>