【问题标题】:Jquery append methosjQuery追加方法
【发布时间】:2014-10-31 06:25:18
【问题描述】:
<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 标记时附加一些文本。

【问题讨论】:

  • 你想在哪里添加文字?
  • 在您的示例中没有li 有一个ul 作为孩子
  • @steo - 实际上,其中一个可以!
  • @adeneo 对不起,对

标签: javascript jquery jquery-selectors jquery-append


【解决方案1】:

幸运的是,jQuery 有一个 :has() 选择器

$('li:has(ul) > a').append('something');

FIDDLE

【讨论】:

【解决方案2】:

看起来你想把文字放在&lt;a&gt;中,所以一旦你找到&lt;li&gt;s,寻找&lt;a&gt;的孩子

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

【讨论】:

    【解决方案3】:
    $('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');
    

    【讨论】:

      【解决方案4】:
      <!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>
      

      【讨论】:

        猜你喜欢
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 2013-04-12
        • 2020-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多