Jquery - 从html编码的字符串中减去src数据

时间:2011-09-19 14:16:59

标签: jquery xml

我在解析XML Feed时遇到问题 - 以下代码尝试解析XML Feed并使用新闻数据填充页面。我的问题是描述节点是HTML编码的,我需要去除其中包含的img标签的src(每个描述节点中只包含一个图像标记)。

我对正则表达式的了解有限 - 但我尝试使用过滤器方法去除src代码 - 但下面的示例不起作用。

任何帮助都会感激不尽,因为我正在用这个把头发拉出来!

$(xml).find("item").each(function() {
    var i = $(xml).find("item").index(this);

    var imgStripSrc = $('item:eq(1) description', xml).filter(function() {
        return /(?: src=")(.+)(?:")/
    })

    if (i < 1) {
        var newsTitleOne = $('item:eq(0) title', xml).text();
        if (newsTitleOne.length > 40) {
            newsTitleOne = newsTitleOne.substring(0, 30) + "..";
        }
        $(".newsIOne .newsText .t").empty();
        $(".newsIOne .newsText .t").append(newsTitleOne);
    } else {
        var newsTitleGen = $('item:eq(' + i + ') title', xml).text();
        if (newsTitleGen.length > 80) {
            newsTitleGen = newsTitleGen.substring(0, 74) + "..";
        }
        var newsTitleLinkHid = $('item:eq(' + i + ') link', xml).text();
        var newsRow = $('<div class="newsRow"><a href="' + newsTitleLinkHid + '" target="_blank">' + newsTitleGen + '</a><img src=' + imgStripSrc + '/></div>');
        $(".newsRows").prepend(newsRow);
    }
});

此处的XML示例 - http://fb.mobilechilli.com/chilli_news_reviews/NewsReviews%20Build/tstXML.xml

1 个答案:

答案 0 :(得分:1)

您可以利用jQuery可以从HTML字符串构建DOM的事实,因此您无需在所有中使用正则表达式。我重写了你的代码:

$(".newsIOne .newsText .t").empty();
$(xml).find("item").each(function(i) {
    var html     = $( $("description", this).text() ), 
        imgsrc   = $("img:first", html).attr("src"),
        title    = $("title", this).text(),
        link     = $("link", this).text(),
        ellipsis = String.fromCharCode(8230);

    if (i == 0) {
        if (title.length > 40) {
            title = $.trim( title.substring(0, 30) ) + ellipsis;
        }
        $(".newsIOne .newsText .t").text(title);
    } else {
        if (title.length > 80) {
            title = $.trim( title.substring(0, 74) ) + ellipsis;
        }
        $(".newsRows").prepend(
            $('<div class="newsRow">')
            .append("<a>", {target: "_blank",  href: link, text: title});
            .append("<img>", {src: imgsrc});
        );
    }
});

注释

  • this始终引用您正在处理的当前元素,因此在each()的正文中,您不必耍弄那些$('item:eq(' + i + ') title', xml)
  • $(description, this).text()获取HTML字符串,将其包装在另一个$()中,从中创建一个DOM。您可以对其进行操作以找到<img>
  • 有一个实际的省略号字符("…"),请使用它。
  • 根据您自己的危险从连接字符串构建HTML。我已经使用了jQuery内置的方便帮助函数。
  • 循环索引作为each()的参数传入,无需自行查找/计算。