简体   繁体   中英

Add css attribute from a javascript variable to a html element with jquery

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">

Refer : HTML attribute with/without quotes

I believe you should learn how CSS and JavaScript work. There are loads of mistakes:

  1. You don't have " . It should be <div id="wrapper"> . And remove the # .
  2. You should concatenate using + operator.
  3. Always make sure you put it inside $(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.

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