简体   繁体   中英

Image not found when replacing background-image with jQuery

As a proof of concept, I am attempting to change the background-image of a div using jQuery with the same image as the original.

The original css is:

CSS

.content {
  background-image: url("test.jpg");
}

jQuery inside a wrapper:

$('.content').css("background-image", 'url(test.jpg)');

I can see that jQuery is firing off fine, and replaces the image (and have verified in Firebug that the CSS is exactly the same), but for some reason, after the jQuery fires, the browser "Could not load the image".

The computed CSS is exactly the same. If I deselect the in-line rule thrown in by jQuery, the old rule is activated and the image appears.

Why would the browser treat the rule differently when injected in-line vs. when it is in the CSS file?

You have a typo in your jQuery:

$('.content').css("background-image", 'url(test.jpg)');

should be:

$('.content').css("background-image", 'url("test.jpg")');

The missing quotes is not the issue. The issue is the path to the image .

If the image is in the same folder as the page, then you can use test.jpg .

If the images are in a different folder on your site, then you need to include the relative path to that image:

$('.content').css("background-image", 'url(../images/test.jpg)');
$('.content').css("background-image", 'url(test.jpg)');

Replace with

$('.content').css("background-image", 'url("test.jpg")');

Notice the lack of quote marks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM