简体   繁体   中英

Setting options in a method call with an array

How can I make it so the .slider() method uses the values from the array?

I have this same slider I have to set up several times, so I figured I would call it once, and input the values with the index. This might not be the way to do it but it's what came to me.

I wanted to step through and change the index number each time I call the slider so it would update to the next 6 values. I realize this code doesn't work, it's just for explaining.

var yolo = ["yield", "true", "15.2", "308", "0.3", "[75.8, 241.4]", "tensile", "true", "37.7", "345", "[81.2, 243.3]"];

     $( yolo[0] ).slider({
        range: yolo[1],
        min: yolo[2],
        max: yolo[3],
        step : yolo[4],
        values: yolo[5],

        slide: function( event, ui ) {
            $( "#" + yolo[0] + "-value" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
        }
     }); //When done, call again, just that updating the index numbers to the next 6

Maybe an .each() with $.extend() ?

You can do something as:

var settings = {
    "yield" : {
         range: true,
         etc..
    },
    "yield2" : {
         range: true,
         etc..
    }
}

$.each(settings, function(key, value){
    var _key = key;
    $( "#" + _key ).slider(
        $.extend(value, {    
            slide: function( event, ui ) {
                $( "#" + _key + "-value" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
            }
        })
    );
});

Extra info:

  1. jQuery.extend
  2. jQuery.each

使用.each http://api.jquery.com/each/遍历数组。

Instead of using an array, you can just use a plain object:

var yolo = {
   range : true,
   min : 15.2,
   max : 308,
   slide : function(){}
};

and then pass that into slider.

$(...).slider(yolo);

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