【问题标题】:variable amount of optional parameters可变数量的可选参数
【发布时间】:2017-10-25 19:27:00
【问题描述】:

我在这里使用这个工具http://craftpip.github.io/jquery-confirm/#dialog,我希望有一个弹出窗口,它基于用于构建弹出窗口的一段数据具有可变数量的按钮。

这是一个非常简单/空的示例。

$.confirm({
    title: 'testing',
    content: 'this has two static buttons',
    buttons: {
        confirm: function () {
        },
        cancel: function () {
        },
    }
});

我想要的是能够在“按钮:{ ... }”旁边放置一个 foreach 循环。

有没有办法这样做或实现我想要做的事情?

【问题讨论】:

    标签: javascript jquery optional-parameters jconfirm


    【解决方案1】:

    只需在之前构建您的选项对象:

    var options = {
        title: 'testing',
        content: 'this has two static buttons',
        buttons: {},
    };
    
    $.each( variable_name, function(){
        options.buttons[ this.btn_name ] = this.fn;
    } );
    
    $.confirm( options );
    

    当然,一切都取决于你循环的对象的样子,但逻辑就在这里。

    【讨论】:

    • 谢谢,这很可能是我最终要做的事情。
    【解决方案2】:

    你的逻辑是颠倒的。下面是一个对象:

    {
        title: 'testing',
        content: 'this has two static buttons',
        buttons: {
            confirm: function () {
            },
            cancel: function () {
            },
        }
    }
    

    所以你可以这样做:

    var options = {
        title: 'testing',
        content: 'this has two static buttons',
        buttons: {
            confirm: function () {
            },
            cancel: function () {
            },
        }
    };
    $.confirm(options);
    

    然后您可以通过添加项目

    options.buttons["mybutton"] = function() { };
    

    您可以将前面的代码放在一个循环中,并将字符串“mybutton”更改为您想要的任何功能。你基本上是在问how to add a property to and existing javascript object

    【讨论】:

    • 谢谢。我对 javascript/jquery 超级陌生,我不明白这种语法是什么。知道这是构建对象的简便方法有很大帮助。
    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2020-03-16
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多