1

我正在为我的网络应用程序创建一个简单的 jQuery 插件。现在我正在添加一个“设置”选项,可用于更改所选元素的默认 CSS:

html

<script type="text/javascript">
   var mycss = {tagNormalStyle: {backgroundColor: '#ddd', color:'#222'}};
    $(document).ready(function(){
        $("#tag1").tagme(mycss);    
        $("#tag2").tagme(null);
    });
</script>       

jQuery插件

$.fn.tagme = function(options) {

// some defaults
var settings = $.extend({
        tagNormalStyle:{
            backgroundColor: 'black',
            color: 'white',
            marginLeft: '5px',
            marginTop: '5px',
            padding: '5px',
            float: 'left',
            borderRadius: '5px'
        },
      //more stuff here...,
       options
      };
}

在我的代码中,我使用的是类似的东西:

if (condition)
    tag.css = settings.tagNormalStyle;

问题是,如果用户只需要改变颜色怎么办?

var mycss = {tagNormalStyle: {color:'#222'}};
$("#tag1").tagme(mycss);

现在所有的默认设置都消失了tagNormalStyle!如何避免对我的设置对象上的每个 css 属性进行“硬编码”?也许我可以“合并”默认值和选项对象。有任何想法吗?

谢谢!

4

1 回答 1

2

将 true 作为第一个参数传递给扩展函数。就像是:

$.extend(true,obj1,obj2)
于 2013-06-26T18:50:04.880 回答