我有html
DOM
这样我想抓取图片url
。
<img src="constant/spacer.gif" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="constant/spacer.gif" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
我的预期输出: ["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
现在我正在使用此代码
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).attr('style')); // furthur i don't know
});
console.log(arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
&#13;
Furthur我不知道如何抓住
["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
请提前帮助我
答案 0 :(得分:1)
您只需使用
即可var images = document.querySelectorAll('.images-thumb');
var image, arr=[];
for(var i=0; i<images.length;i++){
image = window.getComputedStyle(images[i]).backgroundImage;
arr.push(image.substr(5, image.length-7));
}
console.log(arr);
纯JS方法来获取元素的所有样式。
答案 1 :(得分:1)
用空字符串“”代替不需要的文字:
示例摘录:
arr = [];
$('.images-thumb').each(function() {
arr.push($(this).css("background-image").replace("url(\"", "").replace("\")", ""));
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
答案 2 :(得分:0)
You can give the image path in src attribute, otherwise the script will be like below
arr = [];
$('.images-thumb').each(function(){
var txt = $(this).attr('style');
first = txt.indexOf('(');
second = txt.indexOf(')');
arr.push(txt.substr(first+1,second-first-1));
});
console.log(arr);
Just check once
答案 3 :(得分:0)
您可以使用JQuery css("background-image")
选择器和正则表达式来获得所需的结果。
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).css("background-image").replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''));
});
console.log(arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
&#13;