jQuery使用td值作为img的src

jQuery use td value as src for img

本文关键字:img src 使用 td jQuery      更新时间:2023-09-26

我尝试使用innerWrap将td值包装到图像中,

jQuery( "td[id^='imageList']" ).wrapInner( "<img></img>" );
jQuery( "td[id^='imageList']" ).wrapInner( "<img>" );
jQuery( "td[id^='imageList']" ).wrapInner( "<img src=''>" );

(显然)都失败了。

http://source.to/image.png 

<img>http://source.to/image.png</img>

我想要的是

http://source.to/image.png 

变成

<img src="http://source.to/image.png">
谁有解决这个问题的好主意?

您需要创建一个图像并更改源。为此,您可以使用:

jQuery( "td[id^='imageList']" ).each(function(){
    $this = jQuery(this);
    var img = jQuery('<img>', {'src' : $this.text()});
    $this.empty().append(img);
})

您可以使用.wrapInner(function)

使用

jQuery("td[id^='imageList']").wrapInner(function() {
  return "<img src='"+ $(this).text() +"'></img>";
});

这样做:

jQuery( "td[id^='imageList']" ).each(function(){
    var $this = jQuery(this);
    var src = jQuery.trim($this.text());
    $this.html('<img src="'+ src +'">');
});

修剪字符串很好,因为您可能在路径周围也有一些空格。

示例:http://codepen.io/KATT/pen/dqJGA

顺便说一句,我可能会使用class而不是id

示例#2:http://codepen.io/KATT/pen/AjvdK