简体   繁体   中英

How to change css property of content:url in jquery?

I have a problem:

<div id="arrow"></div>
<div id="p0" style="content: url(images/cerchioSelezionato.png)"></div>
<div id="p1" style="content: url(images/cerchio.png)"></div>

My goal is: when i click on #arrow element, I want that the image of #p0 become cerchio and vice versa for this I wrote this code in jQuery:

$(document).ready(function(){
    $("#arrow").click(function(){
       $("#p1").attr({content:url(images/cerchioSelezionato.png)});
       $("#p0").attr({content:url(images/cerchio.png)});
    }
}

When I click on arrow in chrome the console gives me this error:

Uncaught ReferenceError: url is not defined 
slider_script.js:12(anonymous function)     slider_script.js:12m.event.dispatch jquery-1.11.1.min.js:3r.handle

Use .css() instead of .attr() to manipulate the style. Also, I think you forgot to quote.

$(document).ready(function(){
    $("#arrow").click(function(){
       $("#p1").css({content:'url(images/cerchioSelezionato.png)'});
       $("#p0").css({content:'url(images/cerchio.png)'});
    });
});

While the keys don't have to be quoted in Javascript object, the values have to be.

Since you only change the content you can use the syntax .css('content', ... ) instead of the object notaion. I kept it the way you did it so you may add rules in the future.

Try ...

$(document).ready(function(){
    $("#arrow").click(function(){
       $("#p1").attr({style: "content:url(images/cerchioSelezionato.png)" });
       $("#p0").attr({style: "content:url(images/cerchio.png)" });
    }
}

You're changing the Style attribute, but the content attribute.

you can try this one also

$(document).ready(function(){
    $("#arrow").click(function(){
       $("#p1").css('content','url(images/cerchioSelezionato.png)');
       $("#p0").css('content','url(images/cerchio.png)');
    }
}

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