简体   繁体   中英

including “-” in $.extend from jquery

I am trying to create simple Jquery plugin. 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.

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.

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. It can not be used in variable naming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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