Get image src without loading the image?

时间:2015-06-30 19:27:33

标签: javascript jquery html image

I have a html snippet being returned through ajax. The snippet is an <img> tag.

<img src="image.jpg" />

I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.

I have the following code currently extracting the src attribute:

var src = $(value).attr('src');

However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.

How can I extract the value of the src attribute without causing the browser to load the image?

6 个答案:

答案 0 :(得分:3)

我通过在将src属性加载到jquery之前更改其名称来解决这个问题。

 value = value.replace('src', 'data-src');
 var src = $(value).attr('data-src');

这样做可以让我在不使浏览器尝试加载图像的情况下提取值。

答案 1 :(得分:2)

您最好的选择可能是在图像上输出数据标签。然后,您可以使用jQuery对其进行操作,然后使用它来编写最终的图像路径。

所以你要在HTML中做这样的事情:

<img data-img-src="abc.jpg" class="my-image" />

然后在你的jQuery中:

var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
编辑:对不起,我只是重读了它通过AJAX来的地方。在这种情况下,您可以使用ajax请求的数据回调来从图像中去除src。

答案 2 :(得分:2)

$.ajax('someURL.html', function(data){
    var html = data.replace(/\ssrc/g, ' data-src'),
        img  = $(html),
        src = 'some/path/' + img.data('src');
    img.attr('src', src);
    $('#container').append(img);
});

答案 3 :(得分:1)

如果你有字符串,比如<img src="image.jpg" />为什么不去正则表达式?

类似于:/[\"\'][a-z0-9A-Z\.]*/。 PS:我的正则表达式技能很差,所以你可以相应地操纵它。

答案 4 :(得分:1)

使用

var string = '<img src="image.png">';

var matches = string.match(/src\=("|')(.*?)\1/);

console.log(matches[2]);

答案 5 :(得分:1)

您可以在访问后删除该属性。

这不会加载无效图像,因为您可以在控制台中确认:

&#13;
&#13;
var s= $('<img src="invalidURL.jpg">'),
    src= s.attr('src');

s.removeAttr('src');
console.log(src);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

删除removeAttr()尝试加载图片。

相关问题