我正在为我的 Summernote 所见即所得创建动态自定义按钮,但我遇到了问题。我想将我正在迭代的数据传递给按钮的渲染函数,但由于它已经作为参数传递上下文,所以我在这里有点无能为力。
相关代码如下:
var formButtons = {};
var formButtonIds = [];
if(FormsModule.currentForm) {
for(var i=0; i<FormsModule.currentForm.fields.length; i++) {
var field = FormsModule.currentForm.fields[i];
var fieldId = 'button_' + i;
formButtons[fieldId] = (function (context) {
console.log(context);
console.log(field);
var ui = $.summernote.ui;
var tooltip = 'Insert ' + field.title;
// create button
var button = ui.button({
contents: HelperModule.getTitle(field.title),
tooltip: tooltip,
click: function () {
context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
},
});
return button.render();
});
formButtonIds.push(fieldId);
}
}
$("#form-modal #form-form .wysiwyg").each(function(index, wysiwyg) {
var content = $(wysiwyg).summernote('code');
$(wysiwyg).summernote('destroy');
$(wysiwyg).summernote({
buttons: formButtons,
toolbar: [
["style", ["style"]],
['font', ['bold', 'underline', 'clear']],
//['fontname', ['fontname']],
["color", ["color"]],
["para", ["ul", "ol", "paragraph"]],
["mybutton", formButtonIds],
["table", ["table"]],
["insert", ["link"]],
["view", ["codeview"]],
],
});
$(wysiwyg).summernote('code', content);
})
如果我尝试将该字段传递给 formButtons[x] 函数,它(替换上下文的值):
formButtons[fieldId] = (function (context) {
console.log(context);
console.log(field);
var ui = $.summernote.ui;
var tooltip = 'Insert ' + field.title;
// create button
var button = ui.button({
contents: HelperModule.getTitle(field.title),
tooltip: tooltip,
click: function () {
context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
},
});
return button.render();
})(field);
field和context的console.log都是字段值
在我看来,好像在点击时渲染了 field.title,当它超出范围时。
试试这个:
formButtons[fieldId] = (function(context) {
console.log(context);
console.log(field);
var ui = $.summernote.ui;
var tooltip = 'Insert ' + field.title;
// create button
var button = ui.button({
contents: HelperModule.getTitle(field.title),
tooltip: tooltip,
data: { fieldtitle: field.title },
click: function() {
context.invoke("editor.insertText", `<span clas="field-input-button">#${this.dataset.fieldtitle}#</span>`);
},
});
return button.render();
})(field);