3

有没有办法在 init 之后将自定义动态元素添加到 tinyMCE 4.x 中的上下文菜单?我创建了自定义菜单项,但其中许多都有依赖于我的应用程序中发生的其他事情的子项。

我尝试使用editor.on('contextmenu'),但菜单仍然没有更新。有任何想法吗?

4

3 回答 3

3
  1. 添加contextmenu插件
  2. contextmenu通过定义选项覆盖默认上下文菜单(某些插件会自动添加自己的条目) 。它是一个以竖线分隔的自定义菜单项列表(您在步骤 3 中定义)
  3. 定义自定义菜单项列表。这些可以有自己的onclick事件处理程序,或定义子菜单。

tinymce.init({
    ...
    plugins: [..., 'contextmenu'],
    contextmenu: 'customItem1 | customItem2',
    setup: function (editor) {
        editor.addMenuItem('customItem1', {
            text: 'Menu Item 1',
            context: 'tools',
            onclick: function () {
                alert('Menu item 1 clicked');
            }
        });
        editor.addMenuItem('customItem2', {
            text: 'Menu Item 2',
            context: 'tools',
            menu: [ {
                text: "Sub-menu item 1",
                onclick: function () {
                    alert('Sub-menu item 1');
                }
            }, {
                text: "Sub-menu item 2",
                onclick: function () {
                    alert('Sub-menu item 2');
                }
            }]
        });
    }
});

参考:

于 2018-01-09T20:16:10.143 回答
0

对的,这是可能的。JavaScript 对象函数可用于在编辑器事件中动态声明值。即使您可以进行循环,但动态中仅支持一个菜单(因为上下文菜单值是唯一的)制作虚拟上下文菜单并单独声明(应用您自己的逻辑)。

在子菜单上:要创建动态菜单,请使用数组并通过循环中的 JavaScript 对象方法将其推送以动态显示。

供参考:使用 AngularJs 在自定义 TinyMCE 编辑器中添加动态数据

于 2020-07-15T14:20:01.870 回答
0

我就是这样做的,我使用 jQuery $.each 来遍历我的对象,你也可以使用 vanilla JavaScript

//register plugin to process context menu on a specific tag
tinymce.PluginManager.add('contextmenu-plugin', function (editor) {
  var selectedCode
  // Create a function which returns an array of items, these can be Submenus or Simple Items
  var contextMenuItems = () => { 
    return [
    {
      type: 'submenu',
      text: "Submenu 1",
      getSubmenuItems: () => {
        if (selectedCode){
          var contextMenuItems = []
          $.each( ArrayWithData, (index, data ) => {
            contextMenuItems.push({
              type: 'item',
              text: `${data}`,
              onAction: () => {
                console.log("Clicked submenu option");
              }
            })
          })
          // return array of contextmenuitems -> this goes to the Submenu
          return contextMenuItems
        }
       }
      },
      {  
       icon: 'remove',
       text: 'Remove data',
       onAction: () => {
         console.log(`Removed data`)
       }
      }
      }
      ]
      }

// now register the contextmenu
editor.ui.registry.addContextMenu('contextmenu', {
  update: function (element) {
    //this way you can call contextMenuItems() every time you show the context menu
    return (element.tagName == "your-condition" && element.className.includes("another condition") ) ? contextMenuItems() : ""
        }
      });
    });
于 2021-05-01T13:47:55.260 回答