开发者

jQuery: list appended not displaying bullets

开发者 https://www.devze.com 2022-12-28 02:13 出处:网络
I have the following html: <!DOCTYPE html> <html> <head> <script src=\"http://code.jquery.com/jquery-latest.js\"></script>

I have the following 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 tex开发者_JAVA技巧t">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>

I want to retrieve the text within a 'span' whose title attribute contains "specific text", in this case "important 1", "important 2" and "important 3". Then I want to list them below just like the example. However the bullets do not appear, why is that? Any hints would be appreciated!

EDIT: http://jsfiddle.net/XTqjC/3/ this is the code that does what I need it to do. Thanks to Glen and meo


In your example you haven't closed your <ul> properly (missing the slash). Is that a copy+paste error, or in your code as well?

Edit: And you need it is good practice to have a semi-colon after your each() (see comments):

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

Try the following:

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>');
    });

Of course, the $(this).text() won't allow you to place the <img> in the <li>s. So you'll end up with an empty <li></li> for each. This could be fixed with the following:

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


I have corrected your code. You had some errors:

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

here is my version:

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>');
    })

when you do this: var ul = $('body').append($('<ul>'));

the ul variable contains the body, and your li's where not appended to the UL but the body. and when you use append you dont have to put the $() around

0

精彩评论

暂无评论...
验证码 换一张
取 消