0

我的目标是使用 jquery 收集所有插入到 html 代码中的图像 url,如下所示:

style="background: url(...)"

或者

style="background-image: url(...)"

在第一个示例中,可能存在不同的情况(例如添加重复、位置和更改标签的顺序)。

我想正则表达式将是最好的方法,但我不是很擅长。

谢谢!

4

2 回答 2

2

你可以做:

$('[style*="background"]').each(function(){
  // do something with each
});

这将遍历所有具有 inlinestylebackground设置为它们的元素。

请注意,这*=意味着其中某处stylebackground关键字。

于 2012-02-13T06:29:20.953 回答
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,而背景可能没有图像,则正则表达式应该更复杂,并且为了代码可维护性,我将简单地添加另一个“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/

于 2012-02-13T07:06:18.770 回答