Selecting all the divs with png background-image

半城伤御伤魂 提交于 2019-12-23 12:36:35

问题


How can I select in jQuery all the divs that have background-image: url(somepath/somename.png) in their style?


回答1:


There isn't a jQuery selector, but this might work:

$('div').each( function() {
    if ( $(this).css('background-image') == 'url("image.png")' ) {
        // do something here
    }
});

However, a more efficient method would be to make sure you only have a single class that uses that background image, then simply select $('.bgClass')




回答2:


Try adding a custom selector:

$(document).ready(function() { 
    $.extend($.expr[':'], { 
        hasMyImage: function(el) { 
            return ($(el).css('background-image') == "Url('somepath/somename.png')");
        } 
    }); 
}); 

Then to select:

$("div:hasMyImage");



回答3:


Use the filter function:

var matches = $("div").filter(function() 
{      
    return ($(this).css("background-image") == "url('somepath/somename.png')");
});


来源:https://stackoverflow.com/questions/2251874/selecting-all-the-divs-with-png-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!