如何在jquery中动态设置一个属性?

How to dynamically set a property in jquery?

我正在使用 toastr 并希望使用从 ajax 调用返回的 json 对象设置选项。我在动态设置选项 属性 和值时遇到了一些问题。这是示例代码:

if(data.toast){
    $.each(data.toast, function(index, element) {
    toastr.options.index = element;
    });
}

而 data.toast 是一个 json 对象,如下所示:

"toast":{"closeButton":true}

这是我硬编码后的样子:

toastr.options.closeButton = true;

我应该将迭代器中的 .index 更改为什么,以便它将其评估为变量

if(data.toast){
    $.each(data.toast, function(index, element) {
    toastr.options[index] = element;
    });
}

作为 options.index 尝试访问 index 的 属性 而不是索引的 value 的 属性 .

上述方法可以解决这个问题。它将对象视为一种关联数组。所以 toastr.options[index] 计算为 toastr.options["closeButton"]toastr.options.closeButton.

相同