2

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

<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 的情况下实现同样的目标?

4

3 回答 3

3

好吧,您想对其进行一些简单的 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, ''); 
}

jsFiddle 演示

于 2013-10-29T14:57:09.743 回答
1

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

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('"')));
于 2013-10-29T14:57:08.407 回答
0

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

<script>
  var div = document.getElementById("imgDiv");
  var image = div.getElementsByTagName("img")[0];
  alert(image.src);
</script>
于 2013-10-29T15:06:25.447 回答