Jquery parseHTML没有给出预期的对象

时间:2013-05-02 03:12:30

标签: javascript jquery html parsing

鉴于我在javascript变量" data"

中有这个html字符串
<div class="packery-item">        
        <img class="rsImg" src="/media/VERSIONS/images/blog/2013/04/heart-watercolor1_featured_image.jpg" alt="Article illustration"/>        
</div>
<div class="packery-item">        
        <img class="rsImg" src="/media/VERSIONS/images/blog/2013/04/planning_featured_image.jpg" alt="Article illustration"/>        
</div>
<div class="packery-item">
    <img src="/media/VERSIONS/images/galleries/2013/04/fashion_slideshow.jpg" alt="" />
</div>

当我运行$(data)时,它会返回如下内容:

[div.packery-item, text, div.packery-item, text, div.packery-item, text, div.packery-item, text, div.packery-item, text, div.packery-item, constructor: function, init: function, selector: "", jquery: "1.8.3", size: function…]

我希望它只返回一个div.packery-item列表。我做错了什么?

1 个答案:

答案 0 :(得分:0)

你需要摆脱标签之间的空白,它们会变成文本节点,以便元素之间有间距。

var data = '<div class="packery-item">' +
        '<img class="rsImg" src="/media/VERSIONS/images/blog/2013/04/heart-watercolor1_featured_image.jpg" alt="Article illustration"/>' +
'</div>' +
'<div class="packery-item">' +
        '<img class="rsImg" src="/media/VERSIONS/images/blog/2013/04/planning_featured_image.jpg" alt="Article illustration"/>' +
'</div>' +
'<div class="packery-item">' +
    '<img src="/media/VERSIONS/images/galleries/2013/04/fashion_slideshow.jpg" alt="" />' +
'</div>'