jquery select element based on background image name

末鹿安然 提交于 2019-12-08 08:42:50

问题


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.



来源:https://stackoverflow.com/questions/3249881/jquery-select-element-based-on-background-image-name

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