TinyMCE上下文感知动态菜单开发技术问询
Got it, let's walk through a practical implementation that meets your exact requirements—this menu will dynamically enable/disable and update its sub-items based on the table's class prefix:
tinymce.init({ // ... your existing TinyMCE configuration ... setup: function(editor) { // Add the base table_entity menu to the right-click context menu editor.addMenuItem('table_entity', { text: 'Table Entity Actions', context: 'contextmenu', onPostRender: function() { const menuItem = this; // Bind to NodeChange event to update menu state whenever selection changes editor.on('NodeChange', function(e) { // Find the closest parent table from the currently selected element const tableEl = editor.dom.getParent(e.element, 'table'); let hasValidPrefix = false; let extractedPrefix = ''; if (tableEl) { // Check if the table has a class starting with 'prefix_' const tableClasses = tableEl.className.split(' '); for (const cls of tableClasses) { if (cls.startsWith('prefix_')) { hasValidPrefix = true; extractedPrefix = cls.replace('prefix_', ''); break; } } } // Disable menu and clear sub-items if no valid table/prefix exists menuItem.disabled(!hasValidPrefix); menuItem.removeAll(); // Populate dynamic sub-items if valid prefix is found if (hasValidPrefix) { menuItem.add({ text: `Edit ${extractedPrefix} Entity`, onclick: function() { // Replace with your actual edit logic (e.g., open modal, make API call) alert(`Initiating edit for ${extractedPrefix} entity`); } }); menuItem.add({ text: `Delete ${extractedPrefix} Entity`, onclick: function() { // Replace with your actual delete logic alert(`Initiating delete for ${extractedPrefix} entity`); } }); // Add more custom sub-items here based on the extracted prefix } }); } }); } });
Key Details to Note:
- Base Menu Attachment: We use
editor.addMenuItemwithcontext: 'contextmenu'to tie the menu to TinyMCE's right-click menu system. - Dynamic Updates: The
NodeChangeevent listener triggers every time the user selects a different element, ensuring the menu reflects the current context. - Class Prefix Check: We scan the parent table's classes to detect if it has the
prefix_prefix—adjust this string to match your actual target prefix (e.g.,entity_). - Menu State Management:
- No valid table/prefix? Disable the menu and clear all sub-items to avoid confusion.
- Valid prefix found? Enable the menu and add sub-items tailored to the extracted prefix value.
Customization Tips:
- Swap out the
onclickhandler logic with your actual business code (like opening an edit modal, triggering API requests, etc.). - Add conditional sub-items based on the
extractedPrefixvalue—for example, different actions forprefix_uservsprefix_product.
内容的提问来源于stack exchange,提问作者Gosha
相关产品推荐
相关产品推荐

