简体   繁体   中英

JavaScript/jQuery remove double quote from inline background URL Firefox?

Why is Firefox adding double quote to background url?

So I have something like this:

<div id="image" style="background-image:url(http://domain.com/images/img.jpg)"></div>

Now I want to replace image using jQuery on click event:

$("#replace").on('click', function() {
        $("#image").css({'background-image': 'url(http://domain.com/images/img2.jpg)'});
});

Everything works fine, but in Firebug, I can see double quotes:

url("http://domain.com/images/img2.jpg")

and this messes up my HTML, when saving and reloading.

I have tried to remove quotes using

$("#image").css({'background-image': ('url(http://domain.com/images/img2.jpg)').replace(/\"/g, "")});

but it does not work.

Is there a way to prevent?

There is an typo in your HTML:

<div id="image style="background-image:url(http://domain.com/images/img.jpg)"></div>

It should be like:

<div id="image" <------- close this id attribute here

 $(function() { $("#btn").on('click', function(e) { $("#img-block").css("background-image", "url('https://s3-us-west-1.amazonaws.com/powr/defaults/image-slider2.jpg')"); }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="img-block" style="background-image: url('http://wowslider.com/sliders/demo-23/data1/images/hohenschwangau532864.jpg');"> Hello World! </div> <button id="btn"> Replace </button> 

Hope this helps!

What you are seeing is the computed values. Whenever you set style properties, the value gets parsed and normalized to however the browser likes to display them.

When you see url("...") in your style attribute via the developer tools (Firebug or built-in), it's actually not breaking your HTML. It's just displaying the unencoded attribute, so you don't have to look at things like &amp; which is what the underlying HTML would be.

For the most part, you can just ignore this little quirk. You can't really make the browser change the way it presents these properties.

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