jquery select element based on background image na

2019-06-05 22:42发布

问题:

I'm trying to select a div with a certain background image this is what I have so far. Not working. Any ideas of what I'm doing wrong? I'm trying to follow the jQuery documentation.

var markerShadow0 = $("div[background-image='url(\"http://www.axtsweapons.com/gmarkers/markershadowA.png\")]");

回答1:

background-image is not an attribute of the element but a css style.

You will have to iterate all divs and check the css style.

$("div").each( function(){

   if ( $(this).css('background-image') === 'http://www.axtsweapons.com/gmarkers/markershadowA.png' ) {

      //do something

      //stop loop
      return false;

   }


});


回答2:

Are you missing a single tick after the closing parenthesis for the url? I see an opening tick, but no closing one.



回答3:

I don't believe you can treat CSS properties as attributes, which is what you're doing with the div[attribute=value] selector.

You might be able to get div[style*=background-image:url(http://...)] to work (see this), but you'd probably be better off with something like:

$('div').each(function(i, e) {
  if ($(e).css('background-image') == 'http://www.axtsw...dowA.png')) {
    // element matches
  }
});

Note that this will check every div on the page. If you can select some common parent element by ID you'll drastically reduce the number of elements you'll be iterating over.



回答4:

Background image isn't an attribute of a division, it is an attribute of a style. That means you would have to grab the division with that style.