代码之家  ›  专栏  ›  技术社区  ›  tilly

无法用jquery删除img的属性

  •  0
  • tilly  · 技术社区  · 6 年前

    我有一个HTML字符串,在将其发送到服务器之前要对其进行编辑。HTML字符串包含一个或多个img元素。在这些图像元素中,我想删除 src 属性,它是base64字符串。

    不幸的是,使用下面的代码,它会删除整个图像元素。有人知道我做错了什么吗?

    post.content是HTML字符串。我想在这个字符串中找到图像元素,然后为每个图像更改 SRC 属性

    // Remove the base 64 src
    const $content = $(post.content);
    const $img = $content.find('img');
    $img.each(function(i) {
        $(this).attr('src', 'dummy');
    });
    post.content = $content.html();
    console.log(post.content);
    

    使用上述jquery时post.content日志的结果

    <br>
    

    当我不使用上面的jquery时,post.content的结果,一个普通的html字符串和带有base64-src的img

    enter image description here

    编辑1:我做了一个console.log $content ,下面是一个console.log $img

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   lthh89vt    6 年前

    作为你 post.content 包含多个节点。所以当jquery解析它时,它将返回一个多个数组 <p> 节点。

    那么最后 post.content = $content.html(); 只包含第一个节点的内容。

    尝试将整个post.content包装在 <div> 这样地:

    const $content = $("<div>").html(post.content);

    请在此处查看完整代码: https://jsfiddle.net/vzxq0ckf/1/