我的目标是收集所有插入html代码中的jquery的图片网址,如下所示:
style="background: url(...)"
或
style="background-image: url(...)"
在第一个示例中,可能存在不同的情况(例如添加重复,位置和更改标记的顺序)。
我认为正则表达式是最好的方法, 但我不是很擅长。
谢谢!
答案 0 :(得分:2)
你可以这样做:
$('[style*="background"]').each(function(){
// do something with each
});
这将循环遍历设置为内联style
和background
的所有元素。
请注意,*=
表示style
中的某个地方background
有{{1}}个关键字。
答案 1 :(得分:1)
是的。我会选择正则表达式。
以下是一个例子:
var img_urls=[];
$('[style*="background"]').each(function() {
var style = $(this).attr('style');
var pattern = /background.*?url\('(.*?)'\)/g
var match = pattern.exec(style);
if (match) {
img_urls.push(match[1]);
//just for testing, not needed:
$('#result').append('<li>'+match[1]+'</li>');
}
});
如果可以使用不属于背景的样式的url,而背景可能没有图像,则regexp应该更复杂,并且为了代码可维护性,我只需添加另一个“if”而不是比使用负前瞻的正则表达式(许多人难以阅读)。
所以,代码就像这样:
var img_urls=[];
$('[style*="background"]').each(function() {
var style = $(this).attr('style');
var pattern = /background(.*?)url\('(.*?)'\)/ig
var match = pattern.exec(style);
if (match && match.length > 0) {
if (match[1].indexOf(';')>0) return;
img_urls.push(match[2]);
//just for testing, not needed:
$('#result').append('<li>'+match[2]+'</li>');
}
});
你可以在这个小提琴上玩它: http://jsfiddle.net/Exceeder/nKPbn/