【问题标题】:find <img> tag inside text string在文本字符串中找到 <img> 标签
【发布时间】:2011-09-29 09:01:13
【问题描述】:

我有一个 xml 文档(来自提要),我从中提取值:

$(feed_data).find("item").each(function() {
    if(count < 3) {
    //Pull attributes out of the current item. $(this) is the current item.
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        var description = $(this).find("description").text();

现在在“描述”中我需要获取img 元素,但这给我带来了一些问题。 “descripttion”是一个常规的字符串元素,我似乎不能在这个上调用“.find()”方法,那我该怎么办?

我试过打电话给.find()

var img = $(this).find("description").find("img");

但这是不行的。 img 被包裹在一个跨度中,但我也无法做到这一点。有什么建议么?我宁愿避免使用子字符串和正则表达式解决方案,但我不知所措。

我还尝试将“描述”字符串转换为 xml 对象,如下所示:

var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml'); 

$(desc).find("img").each(function() {
    alert("something here");
});

但这也不起作用。似乎可以,但我收到“文档格式不正确”的错误。

【问题讨论】:

  • 至少请考虑发布您正在使用的字符串。否则我们只是在猜测如何提供帮助。

标签: javascript jquery xml parsing


【解决方案1】:

尝试将 description 标记的内容包含在一个虚拟 div 中,这对我来说似乎效果更好,并允许 jQuery 的 .find() 按预期工作。

例如

$(feed_data).find("item").each(function() {
    if(count < 3) {
        //Pull attributes out of the current item. $(this) is the current item.
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        var description = '<div>' + $(this).find("description").text() + '</div>';
        var image = $(description).find('img');

【讨论】:

  • 谢谢,这与我最终得到的解决方案相似,我相信这也可以。
【解决方案2】:

您好,感谢您的及时回复。我给了 GregL 打勾,因为我确信他的解决方案会奏效,因为原理与我最终得到的相同。我的解决方案如下所示:

    $(feed_data).find("item").each(function() {
        if(count < 3) {
            //Pull attributes out of the current item. $(this) is the current item.
            var title = $(this).find("title").text();
            var link = $(this).find("link").text();
            var description = $(this).find("description").text();

            var thumbnail = "";
            var temp_container = $("<div></div>");
            temp_container.html(description);
            thumbnail = temp_container.find("img:first").attr("src");

所以将字符串包装在一个div中,然后使用“find()”获取第一个img元素。我现在有了图片源,可以根据需要使用。

【讨论】:

    【解决方案3】:

    也许你应该尝试将描述文本转换为html标签,然后尝试通过jquery遍历它

    $('<div/>').html($(this).find("description").text()).find('img')
    

    注意:未测试

    【讨论】:

    • +1 与我的方法相似,这最终奏效了。
    猜你喜欢
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多