简体   繁体   中英

How to effectively repeat jquery-ui function for multiple identifiers

I have the following javascript (jquery-ui library) function:

$(function() {
    $("#mixerSlider0").slider({
        orientation: "vertical",
        range: "min",
        min: 0,
        max: 100,
        value: 60,
        slide: function(event, ui) {
            $("#mixerInp0").val(ui.value);
        }
    });
    $("#amount0").val($("#mixerInp0").slider("value"));
});

This function works perfect, and now I want to apply the same function for 64 more elements "mixerSliderX", "mixerInpX", and "amountX", where X=0..63.

Now I could simply copy paste this function 63 times, and adjust these identifiers, however I'm sure there's a more logical way to do this, and avoid such a terrible amount of code duplication. However I'm not sure how to go about this, hope somebody can help.

Give them all a class, eg class="mixerSlider" , and a data attribute with the related input ID, data-input="mixerSlider0" .

Also give your #amountX fields a class like .amount so you can operate on them as a group.

$(function() {
    $(".mixerSlider").slider({
        orientation: "vertical",
        range: "min",
        min: 0,
        max: 100,
        value: 60,
        slide: function(event, ui) {
            $('#' + $(this).data("input")).val(ui.value);
        }
    });
    $(".amount").val(function(i) {
        return $("#mixerInp" + i).slider("value");
    });
});

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