javascript 从 img 标签中获取 src 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19342690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the src value from the img tag
提问by prime
I wrote this code part in my JavaScript file to select all img
tags in my .html
file.
我在 JavaScript 文件中编写了此代码部分,以选择文件中的所有img
标签.html
。
var imgs = document.getElementsByTagName('img');
How can I extract the src
values of those tags to an array for future use?
如何src
将这些标签的值提取到数组中以备将来使用?
回答by Joke_Sense10
Use src tag:
使用 src 标签:
var imgs = document.getElementsByTagName("img")[0].src;
or
或者
var imgs = document.getElementById("imgid").src;
回答by Dinesh
Just try like this
就这样试试
function img_find() {
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
return imgSrcs;
}
回答by Dan Heberden
Array.prototype.map.call(document.getElementsByTagName('img'), function(img) {
return img.src;
});
This is what mapis for.
这就是地图的用途。
You can also use an empty array:
您还可以使用空数组:
[].map.call(document.getElementsByTagName('img'), function(img) {
return img.src;
});
If needing more browser support or wanting to use a util lib,
如果需要更多浏览器支持或想要使用 util lib,
jQuery.map(document.getElementsByTagName('img'), function(img){ return img.src; });
or just use jQuery the way it's supposed to be used (though the above would work with _.map
, using underscore or lodash):
或者只是按照它应该使用的方式使用 jQuery(尽管上面可以_.map
使用下划线或 lodash):
jQuery('img').map(function(){ return this.src; });
回答by Rahul Tripathi
You may try like this:-
你可以这样尝试:-
var img = document.getElementById('myImg');
var attr = img.getAttribute('src');
or try simply like this:-
或者像这样尝试:-
var imgs = document.getElementById('your_image_id').getAttribute('src');