Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting jQuery .css() within "for .. in" loop

Tags:

jquery

This works OK:

$(container_elm).css({
  'border-width':'1px'
})

Now I am trying to pass CSS propertyName : value as a parameter to a function:

function my_func(css_arr) {
  if (css_arr!==null && css_arr!=='') {
    for(var x in css_arr) {
      if(css_arr.hasOwnProperty(x)) {
        y=css_arr[x];
        x_new='"'+x+'"';
        y_new='"'+y+'"';

        $(container_elm).css({
            //'border-width':'1px' // this works
            //x:y // this does NOT work
            //x_new:y_new // this does NOT work
        });
        //console.log(x_new, y_new); //returns "border-width" "1px"
        //console.log(x, y); //returns border-width 1px
      }
    }
  }
}

//usage
my_func({'border-width':'1px'});

How can I pass CSS object "propertyName : value", and make .css() receive it and work?

Edit

Demo - http://jsfiddle.net/BRwzF/5/

like image 444
ihtus Avatar asked Jun 27 '26 11:06

ihtus


1 Answers

Instead of mucking about with x and x_new, etc, if you're passing in JSON already, why not do this:

$(container_elm).css(
    css_arr
);
like image 94
SomeKittens Avatar answered Jun 30 '26 01:06

SomeKittens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!