从没有jQuery的字符串中获取图像src

get Image src from string without jQuery

本文关键字:获取 图像 src 字符串 jQuery      更新时间:2023-09-26

我有一个字符串(不在我的文档中),比如

<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg"> Freedom is a wonderful thing and the folks at BearExtender want Microsoft users to enjoy more of it. Its new 1,200mW USB WiFi booster for PCs finally caught up with the Mac version, which extends WiFi range up to four times more than usual. One lucky reader will get to savor this new found freedom ...<div>

我想剥离字符串中第一个图像的来源。我知道我可以通过以下方式使用 jquery 来做到这一点: String.find('img').first().attr('src');

没有jquery,我怎么能实现同样的事情?

好吧,

您想对其进行一些简单的JS测试,以从那里剥离src,如下所示:

var str = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg"> Freedom is a wonderful thing and the folks at BearExtender want Microsoft users to enjoy more of it. Its new 1,200mW USB WiFi booster for PCs finally caught up with the Mac version, which extends WiFi range up to four times more than usual. One lucky reader will get to savor this new found freedom ...<div>'
var imgExists = str.indexOf('<img src="');
if (imgExists > -1) {
    var i = imgExists + 10;
    str = str.substr(i);
    str = str.substr(0, str.indexOf('"'));
    alert(str); 
     // returns = http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg 
    // to remove all the spaces you might also want to do another replace after the last 2 substr's
    // str = str.replace(/'s/g, ''); 
}

js小提琴演示

你可以通过以下方式获得它:

var i = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg"> Freedom is a wonderful thing and the folks at BearExtender want Microsoft users to enjoy more of it. Its new 1,200mW USB WiFi booster for PCs finally caught up with the Mac version, which extends WiFi range up to four times more than usual. One lucky reader will get to savor this new found freedom ...<div>';
    alert(i.substring(i.indexOf('http'), i.lastIndexOf('"')));

我可以看到您在div中使用了这个img。将div中的id参数设置为 id="imgDiv" 。然后你可以用这个语法来解决问题:

<script>
  var div = document.getElementById("imgDiv");
  var image = div.getElementsByTagName("img")[0];
  alert(image.src);
</script>