简体   繁体   中英

Use variables in JQuery .css() function

I'm trying to set an image's left and right values randomly using JQuery by doing the following:

var sides = ["left", "right"]
var currentSide = sides[Math.floor(Math.random() * sides.length)];
$("#"+currentImage).css({currentSide : "80px"});

So i have an array that contains either 'left' or 'right' which gets randomly selected and the CSS of the element gets set to either right: "80px"; or left: 80px;

But, its not working. When I go and set it statically eg $("#"+currentImage).css({"left" : "80px"}); then it works fine, so it's just passing variables to the .css() function that's making this break.

Any ideas?

You are trying to create an object with a dynamic key, in that case you need to use bracket notation. In your case you are creating an object with key currentSide not left/right .

You can use

$("#"+currentImage).css(currentSide, "80px");

I'll answer this a bit more generally so you don't run into this type of problem in the future, with other applications that may not have an alternate syntax like $().css() does. Using this method you can also assign multiple styles using a single .css() call.

var sides = ["left", "right"]
var currentSide = sides[Math.floor(Math.random() * sides.length)];
var styles = {};
styles[currentSide] = "80px";
$("#"+currentImage).css(styles);

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