javascript - 如何从 style 属性获取图像 url

标签 javascript jquery node.js

我有 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);
<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">

Furthur 我不知道如何准确抓取

["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];

请帮助我提前致谢

最佳答案

你可以这样做:

url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''); 这将从字符串的开头删除 url('url(")(如果存在)和 ") 以及 ' ) 从末尾开始。

arr = [];

$('.images-thumb').each(function(){

   var $style = $(this).attr('style');
   var $url = $style.replace(/^background-image:url\(["']?/, '').replace(/["']?\)$/, '').replace(/\)/, '');
   arr.push($url); // further know you know :-P
});

console.log(arr);

关于javascript - 如何从 style 属性获取图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902987/

相关文章:

javascript - 如何在 Mongoose MongoDb NodeJS 中获取数组中集合中的连接对象

javascript - Node.js 数据表编辑器 - 根据特定值过滤选择选项

javascript - jquery 单击输入[类型 =''] 不起作用

javascript - AngularJS XMLHttpRequest 无法加载 X。不存在 'Access-Control-Allow-Origin' header

javascript - 工具提示(qTip)未关闭,jQuery

javascript - public_html 中的两个索引文件

javascript - Kendo optionLabel 下拉菜单无法正常工作

javascript - Angular-formly 尝试从不存在的源获取 api 检查

javascript - 在 iframe 中克隆的网站(并且禁用 JavaScript)

Node.JS 等待变量被设置