构建JavaScript对象以与jQuery .css()一起使用(关于重复键?) [英] Build JavaScript Object to use with jQuery .css() (what about duplicate keys?)

查看:96
本文介绍了构建JavaScript对象以与jQuery .css()一起使用(关于重复键?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery的 .css()方法将样式应用到元素。我这样做:

  var cssObj = {
'background-color':'#000',
'background-image':'-webkit-linear-gradient(top,#000,#fff)',
'background-image' '
};

$(。element)。css(cssObj);

问题是显然我在对象中使用了重复的键, / p>

我如何解决这个问题?我需要传递具有重复名称的CSS参数来处理大多数浏览器。

解决方案

有多个相同名称的键无效



创建一个应用 cssObj 的属性的函数/ 。如果找到一个字符串 - 字符串对,设置一个具有所需值的CSS属性。

如果找到一个数组,循环遍历它,并用每个值更新该属性。如果找到无效值,则会被忽略。



演示: http: /jsfiddle.net/RgfQw/

  //为项目可移植性创建了一个插件
(function($){
$ .fn.cssMap = function(map){
var $ element = this;
$ .each(map,function(property,value){
if(value instanceof Array){
for(var i = 0,len = value.length; i< len; i ++){
$ element.css(property,value [i]) ;
}
} else {
$ element.css(property,value);
}
});
}
} (jQuery);

//用法:
var cssObj = {
'background-color':'#000',
'background-image':['-webkit-线性梯度(顶部,#000,#fff)']
};
'
$(。element)。cssMap(cssObj);


I use jQuery's .css() method to apply styles to an element. I do this like so:

var cssObj = {
    'background-color' : '#000',
    'background-image': '-webkit-linear-gradient(top,#000,#fff)',
    'background-image': 'linear-gradient(top,#000,#fff)'
};

$(".element").css(cssObj);

The problem with this is that obviously I use duplicate keys in the object, which is not cool.

How can I solve this problem? I need to pass the CSS params with duplicate names to address most browsers.

解决方案

Having multiple keys with the same name is not valid, and will generate an error in strict mode.

Create a function/plugin which applies the properties of your cssObj. If a string-string pair is found, set a CSS property with the desired value.
If an array is found, loop through it, and update the property with each value. If an invalid value is found, it's ignored.

DEMO: http://jsfiddle.net/RgfQw/

// Created a plugin for project portability
(function($){
    $.fn.cssMap = function(map){
        var $element = this;
        $.each(map, function(property, value){
            if (value instanceof Array) {
                for(var i=0, len=value.length; i<len; i++) {
                    $element.css(property, value[i]);
                }
            } else {
                $element.css(property, value);
            }
        });
    }
})(jQuery);

// Usage:
var cssObj = {
    'background-color': '#000',
    'background-image': ['-webkit-linear-gradient(top,#000,#fff)',
                         'linear-gradient(top,#000,#fff)']
};
$(".element").cssMap(cssObj);

这篇关于构建JavaScript对象以与jQuery .css()一起使用(关于重复键?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆