[英]Add event handler to element in tinyMCE
我正在為 tinymce 開發一個插件,該插件將 HTML 元素添加到編輯器內容中......
這就是我插入代碼的方式:
let el = tinymce.activeEditor.dom.create('div', {'class': 'css-class'}, "this is the text");
tinymce.activeEditor.selection.setNode(el);
現在,如果用戶單擊新的 HTML 元素,我想打開一個對話框。 我試圖添加這樣的事件監聽器
el.addEventListener("click", function() {
console.log("clicked!");
});
但這並沒有做任何事情......
我正在使用 tinyMCE 5.x
您應該參考https://www.tiny.cloud/docs/api/tinymce.dom/tinymce.dom.eventutils/#bind
從您的角度來看,代碼應如下所示:
tinymce.activeEditor.dom.bind(el, 'click', (event) => {/* you function here */})
或者
tinymce.activeEditor.dom.bind(el, 'click', function(event) {/* you function here */})
編輯:
這是一個可行的解決方案,盡管應該有更好的方法來做到這一點
let el = tinymce.activeEditor.dom.create('div', {'class': 'css-class', 'id': "mydiv"}, "this is the text");
tinymce.activeEditor.selection.setNode(el);
tinymce.activeEditor.dom.get("mydiv").addEventListener("click", function() {
console.log("clicked");
});
請注意,來自dom
的get()
function 接受不帶 # 的元素 id
這是一個 TinyMCE Fiddle,它為編輯器中存在的內容添加了點擊偵聽器:
https://fiddle.tiny.cloud/g9haab
I would note that you don't need to use any TinyMCE specific APIs to add a click listener - once you have content in TinyMCE it is effectively an HTML document in an iframe and you can interact with it just as you can any other HTML document . Fiddle 在加載時在編輯器中有一些默認內容:
<p>
This is a paragraph of text that
<span style="color: red; font-weight: bold;" id="target">
contains a span
</span>
to add a click listener
</p>
...然后在設置 function 中有代碼,它使用target
id
查找<span>
並使用標准 JavaScript 附加點擊偵聽器:
const theTarget = editor.contentDocument.getElementById('target');
theTarget.addEventListener("click", function () {
console.log('You CLICKED the text!');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.