动态生成 TinyMCE 下拉菜单

Generating TinyMCE drop-down menu dynamically

我正在尝试使用从数组派生的选项在 TinyMCE 中创建工具栏按钮。我按照 Tiny 网站上的示例进行操作,按钮按预期生成。这是代码:

var mergeFields = {one: "first", two: "second", three: "third"};

tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function (editor) {
    editor.ui.registry.addMenuButton('mergefields', {
        text: 'Merge Fields',
        fetch: function (callback) {
            var items = [];
            for (var fieldName in mergeFields) {
                var menuItem = {
                    type: 'menuitem',
                    text: mergeFields[fieldName],
                    onAction: function() {
                        // The problem: this function always inserts the last element of the array
                        // instead of the expected fieldName associated with this menuItem
                        editor.insertContent(fieldName);
                    },
                };
                items.push(menuItem);
            }
            callback(items);
        },
    });
}
});
<script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=XXXXX"></script>

<textarea>Editor</textarea>

The problem happens when one of the options is selected and the anonymous function assigned to onAction 属性 is executed -- it always inserts "three" into the document (presumably because after 运行 通过整个数组,fieldName 设置为 "three")。如何让 onAction 处理程序将正确的值插入到文档中?

这需要在 TinyMCE 5 中工作。

我在这里发现了一个类似的问题:,但它指的是 TinyMCE 4,不幸的是,提供的答案不适用于 TinyMCE 5。

感谢您的帮助!

我遇到了同样的问题。 我使用 value+onSetup

解决了它

https://jsfiddle.net/stvakis/tjh7k20v/8/

var mergeFields = {
  one: "first",
  two: "second",
  three: "third"
};

tinymce.init({
  selector: 'textarea',
  menubar: false,
  toolbar: 'mergefields',
  setup: function(editor) {
    editor.ui.registry.addMenuButton('mergefields', {
      text: 'Merge Fields',
      fetch: function(callback) {
        var items = [];
        for (var fieldName in mergeFields) {
          var menuItem = {
            type: 'menuitem',
            text: mergeFields[fieldName],
            value:fieldName,
            onSetup: function(buttonApi) {
              var $this = this;
              this.onAction = function() {
                editor.insertContent($this.data.value);
              };
            },
          };
          items.push(menuItem);
        }
        callback(items);
      },
    });
  }
});