最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jQuery's .css() with variable property name? - Stack Overflow

programmeradmin4浏览0评论

Instead of writing:

$('div').css({'backgroundColor': 'red'});

I want to write something like:

$('div').css({get_property_name(): 'red'});

where get_property_name() will return "backgroundColor", "color", "border-top-color", or any other property.

What options do I have to make it work ?

Instead of writing:

$('div').css({'backgroundColor': 'red'});

I want to write something like:

$('div').css({get_property_name(): 'red'});

where get_property_name() will return "backgroundColor", "color", "border-top-color", or any other property.

What options do I have to make it work ?

Share Improve this question asked Sep 20, 2010 at 10:52 Misha MoroshkoMisha Moroshko 171k229 gold badges520 silver badges760 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

The .css() method can also be called as .css(propertyName, value).

$('div').css(get_property_name(), 'red');

If you really need the dictionary representation:

var d = {};
d[get_property_name()] = 'red';
$('div').css(d);

Just assign an object those values and pass it to .css()

var styles;
styles[get_property_name()] = 'red';
$(div).css(styles);
发布评论

评论列表(0)

  1. 暂无评论