找到& lt; img>标记在文本字符串内

find <img> tag inside text string

本文关键字:文本 字符串 lt img 找到      更新时间:2023-09-26

我有一个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元素,但这给我带来了一些问题。"description"是一个常规的字符串元素,似乎我不能调用"。find()"方法,所以我该怎么办?

我试着打电话给.find():

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

但是不行。img被包装在一个span中,但我也无法做到这一点。有什么建议吗?我宁愿避免子字符串和正则表达式的解决方案,但我在一个损失。

我也试过把"description"字符串变成一个xml对象,像这样:

var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml'); 
$(desc).find("img").each(function() {
    alert("something here");
});

但这也不行。看起来是这样的,但是我得到了一个"document not well formed"的错误。

尝试将描述标签的内容封闭在一个虚拟的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');

您好,感谢您的及时回复。我给格雷格打了个勾,因为我确信他的解决方案会起作用,因为原理和我最后得到的是一样的。我的解决方案是这样的:

    $(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元素。我现在有了图像源,可以根据需要使用。

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

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

注释: not testing