代码之家  ›  专栏  ›  技术社区  ›  Dan7

jquery:追加列表但不显示项目符号

  •  1
  • Dan7  · 技术社区  · 16 年前

    我有以下HTML:

    <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      <span>not so important</span>
      <span title="some specific text"><img src="/img/some.gif" /></span>
      <span title="more specific text">important 1</span>
      <span title="more specific text">important 2</span>
      <span title="more specific text">important 3</span>
      <span title="more specific text"><img src="/img/some.gif" /></span>
      <ul>
        <li>example 1</li>
        <li>example 2</li>
        <li>example 3</li>
      <ul>
      <script>
        var ul = $('body').append($('<ul>'));
        $("span[title*='specific text']")
            .contents()
            .filter(function(){ return $(this).nodeType != 1; })
            .each(function(){
                ul.append($('<li>' + $(this).text() + '</li>'));
            })
      </script>
    </body>
    </html>
    

    我想检索一个'SPAN'中的文本,它的title属性包含“特定文本”,在本例中是“important 1”、“important 2”和“important 3”。然后我想像下面的例子一样列出它们。但是子弹没有出现,为什么?任何提示都将不胜感激!

    编辑: http://jsfiddle.net/XTqjC/3/ 这就是我需要的代码。感谢格伦和喵

    2 回复  |  直到 16 年前
        1
  •  4
  •   GlenCrawford    16 年前

    在你的例子中,你没有关闭 <ul> 正确(缺少斜线)。这是复制+粘贴错误,还是在您的代码中?

    编辑: 和 你需要 最好在each()后面加一个分号(见注释):

    .each(function(){
      ul.append('<li>' + $(this).text() + '</li>');
    });
    

    请尝试以下操作:

    var newUL = $('<ul/>');    //due credit to meo (see below)
    $('body').append(newUL);
    $("span[title*='specific text']")
        .contents()
        .filter(function(){ return $(this).nodeType != 1; })
        .each(function(){
            $("body ul").append('<li>' + $(this).text() + '</li>');
        });
    

    当然了, $(this).text() 不允许您放置 <img> 在 <li> 所以你最后会得到一个空的 <li></li> 为每一个。可以通过以下方法解决此问题:

    .each(function(){
      if ($(this).text().trim() != "") {
        $("body ul").append('<li>' + $(this).text() + '</li>');
      }
    });
    
        2
  •  2
  •   meo    16 年前

    我已经更正了你的密码。你犯了一些错误:

    http://jsfiddle.net/XTqjC/2/

    这是我的版本:

    var ul = $('<ul/>');
    $('body').append(ul)
    $("span[title*='specific text']")
        .contents() // you actually don't need contents()
        .filter(function(){ return $(this).nodeType != 1; })
        .each(function(){
            ul.append('<li>' + $(this).text() + '</li>');
        })
    

    当您这样做时: var ul = $('body').append($('<ul>'));

    ul变量包含主体,li不附加到ul而是附加到主体。当你使用append时,你不必把 $() 围绕