简体   繁体   English

在jquery的$ .extend中包括“-”

[英]including “-” in $.extend from jquery

I am trying to create simple Jquery plugin. 我正在尝试创建简单的Jquery插件。 The problem is when I change the name of settings's properties from backgroundcolor1 to background-color1 or just include "-" in the property name, the compiler does not allow me to do it. 问题是,当我将设置的属性名称从backgroundcolor1更改为background-color1或仅在属性名称中包含“-”时,编译器不允许我这样做。

Why is that? 这是为什么?

  (function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundcolor1: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ "color": settings.color, "background-color": settings.backgroundcolor1 }); }; }( jQuery )); $(document).ready(function () { $("h2").greenify({ color:"red",backgroundcolor1:"yellow"}); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h2> for test</h2> 

I have added the code, you can try using background-color1 in place of backgroundcolor1, and you will see that compiler not allowing this. 我已经添加了代码,您可以尝试使用background-color1代替backgroundcolor1,并且您会看到编译器不允许这样做。

You can use quoted object keys: 您可以使用带引号的对象键:

$.fn.greenify = function (options) {
    var settings = $.extend({
        "color": "#556b2f",
        "background-color": "white"
    }, options);

    return this.css({
        "color": settings["color"],
        "background-color": settings["background-color"]
    });
}

$("h2").greenify({ "color": "red", "background-color": "yellow" });

The "-" sign is used as the minus operator in JavaScript and will thus try to calculate the variables instead. “-”符号在JavaScript中用作减号运算符,因此将尝试尝试计算变量。 It can not be used in variable naming. 不能在变量命名中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM