Dom 字符串在使用 jQuery attr 操作后不会改变

Dom string doesn't change after manipulation with jQuery attr

本文关键字:操作 改变 attr jQuery 字符串 Dom      更新时间:2023-09-26

我正在制作一个基于 js 的 epub 阅读器作为周末项目,我正在尝试将本书每个页面上图像的 src 属性从图像 url 更改为从 epub zip 加载的数据 URI。这是我的函数:

//page contents is just an html string of the book's page
pageContents = GlobalZipLoader.load('epub.zip://' + pageLocation);
pageContents = replaceImages(pageContents)
...
function replaceImages(pageContents){
  $(pageContents).find('img').each(function(){
    var domImage = $(this);
    //this is something like ".../Images/img.jpg"
    var imageLocation = domImage.attr('src'); 
    //this returns the proper data-uri representation of the image
    var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);
    //this doesn't seem to "stick"
    domImage.attr('src', dataUri);
  });
  return pageContents;
}

从 replaceImages 函数返回的 pageContents 仍然具有旧的 src 属性。如果需要,我可以提供更多细节,但任何帮助将不胜感激。

正确答案感谢系统重新启动和 Ilia G:

function replaceImages(pageContents) {
    newContent = $(pageContent);
    ... manip ...
    return newContent;
}

你不需要克隆它。只需设置 pageContents = $(pageContents); ,然后在 pageContents 上执行图像替换,然后return pageContents.html();

您应该

尝试在图像加载完成后更改图像src;

我认为这正在loadImage功能中发生。

根据您的更新问题:

我认为你不需要任何clone()。只需将pageContents存储在tempContents变量中并使用该变量

由于 pageContents 只是一个字符串,因此您需要返回它的修改版本。试试这个:

function replaceImages(pageContents){
  // save jQuery object
  var $pageContents = $(pageContents);
  $pageContents.find('img').each(function(){
    var domImage = $(this);
    //this is something like ".../Images/img.jpg"
    var imageLocation = domImage.attr('src'); 
    //this returns the proper data-uri representation of the image
    var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);
    //this doesn't seem to "stick"
    domImage.attr('src', dataUri);
  });
  // return contents of the modified jQuery object
  return $pageContents.html();
}