开发者

modify detached html element (change img.src) with jquery

开发者 https://www.devze.com 2023-03-16 17:05 出处:网络
I want to prefix all src of img tags in an html element. Currently my code looks like this: var html = ...;

I want to prefix all src of img tags in an html element.

Currently my code looks like this:

var html = ...;
$('img[src]', html).each(function(a) {
  var $t = $(this);
  var oldsrc = $t.attr('src');
  $t.attr({src: prefix + oldsrc});
}); 

Another alternative

_.each($('img', html), function(img) {
  var src = base + $(img).attr('src');
  img.src = src;
});

When I run this code on the dom it works flawless. But when I try to run this against an detached html object it won't work. This updates the img within the closure, but does not update html the imgs within html.

What am I missing here?

The solution does not need to use jquery (c开发者_开发知识库an also be plain javascript or backbone)


as @Felix Kling pointed out: html needs to be a DOM Element, but it was a String

html = $(html);

fixed the issue

0

精彩评论

暂无评论...
验证码 换一张
取 消