用Jquery替换图像的源代码

时间:2013-11-13 11:55:40

标签: javascript jquery

我用Phonegap构建应用程序。它从rss提要中获取xml并从中创建html以显示新闻提要。问题是图像路径是相对的。我需要用完整路径替换相对路径。图像标签显示在“description”xml标签内。我得到的描述内容如下:

$(xml).find('item').each(function (index) {

   description = $(this).find('description').text();
   console.log('description');

控制台输出是:

<p>Senior Rugby</p>
<p>CBC v CBS</p>
<p>
  <span class="mjwideimg"><img width="300" height="247" src="/images/latestnews2/Resized/logo_300x247.jpg" alt="logo" />
  </span>
</p>

然后我尝试用完整路径替换路径。我这样做:

$(description).find('img:first').attr('src', 'http://www.domain.com/img/test.png');

然后以完整路径获取新的HTML:

description = $(description).html();
console.log(description);

然而,这只是输出:

Senior Rugby
其他一切都被剥夺了。我做错了什么?

3 个答案:

答案 0 :(得分:0)

当您找到图像时,描述是否仍然设置为$(this).find('description').text();

如果是这样,JQuery对象不是指向HTML元素,而是指向该元素内的一串文本。

尝试使用$(this).find('description');

替换说明

答案 1 :(得分:0)

在你正在做的第一个console.log

description = $(this).find('description').text();
console.log('description');

这里你记录的是xml节点而不是你编码的变量。

另一方面,你做了一些不同的事情(这次是为变量而做的)

description = $(description).html();
console.log(description);

另一点是使用.prop()而不是.attr()

$(description).find('img:first').prop('src', 'http://www.domain.com/img/test.png');

答案 2 :(得分:0)

最后我这样做了:

description = $(this).find('description').text();

$(description).find('img').each(function(i, obj){

   src = $(obj).attr('src');

   //check if not full path 
   if(src.indexOf('http') === -1){
     //therefore its a relative path
     description = description.replace(src,"http://domain.com"+src);
   }
});
相关问题