简体   繁体   中英

jQuery set background image not working

What could be the problem? The console shows me that the variable y contains the right absolute path of an existing external image (direct linking enabled). After the background setting font color turns to red.

console.log("image url: "+y);
       $(this).css("background","url('"+y+"') !important;");
       $(this).css("color","red");

It does not work with background-image either.

Remove the !important; .

Read this if you have to use that declaration: How to apply !important using .css()?

Have you tried this?

$(this).css({
     backgroundImage:"url('"+y+"') !important"
     });

I recommend to use an object when you pass multiple css styles to the same element rather using the .css command multiple times:

$(this).css({
         backgroundImage:"url('"+y+"') !important",
         color: "red"
         });

尝试

$(this).css("background","url('" + y + "') !important");

我将其放在对CSS的单个调用中,例如:

$(this).css({"background":"url('"+y+"') !important", "color":"red"});

As others have stated, it's better to pass an object rather than calling the css function several times. Also, in my opinion, it's more clear if you don't use css shorthands.

Anyways, try it with double quotes in the url.

$(this).css({'background-image':'url("'+y+'") !important', 'color':'red'});

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