2014-09-06 109 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>