Reputation: 5854
Using jQuery v1.6.4,
I'm trying dynamically format some objects.
Here is my code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
style = {'color':'#F30', 'font-size':'20px'};
/* example:1 - not working */
for(attr in style) $('.text').css({attr:style[attr]});
/* example:2 -works */
//$('.text').css({'color':style['color']}).css({'font-size':style['font-size']});
})
</script>
</head>
<body>
<div class="text">This is the text.</div>
</body>
</html>
Why example 1 is not working? Are there some other approach?
Chrome console does not shows any error. Object "style" will be form JSON, so I'm trying to optimize the code, rather to manually write for every style, like in second example.
Thank you for any help.
Upvotes: 1
Views: 181
Reputation: 5412
$('.text').css(style);
The reason it is not working is that you have created a javascript literal object. This is like the json you are using to pass parameters in the second example. It is not going to work as it will not loop over your object and so makes it look malformed. You have already done the hard work, so just pass the styles.
Upvotes: 6