I stored a url in a javascript variable "bg_url" and I want to attach this url to a background-image property to a html element.
my html
<div id=#wrapper>
<p>test</p>
</div>
and my jQuery is like
$("#wrapper").css({ background-image: "'print(bg_url)'" });
but I do not get the variable attached to the css property. Does someone have an idea?
Use camel cased property or use quotes since it contains -
in the property name.
$("#wrapper").css({ backgroundImage: 'url('+ bg_url+ ')' });
// or
$("#wrapper").css({ 'background-image': 'url('+ bg_url+ ')' });
Although there is no need for #
in your id attribute of the element and it's always better to use quotes to wrap the attribute value.
<div id="wrapper">
I believe you should learn how CSS and JavaScript work. There are loads of mistakes:
"
. It should be <div id="wrapper">
. And remove the #
. +
operator. $(function () {})
. Your code should be:
var bg_url = "http://placehold.it/100?text=Background"; $(function () { $("#wrapper").css({ backgroundImage: "url('" + bg_url + "')" // And don't forget the quotes here. }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <p>test</p> </div>
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.