使用 attr 向 TinyMCE 节点添加属性不起作用
Adding attribute to TinyMCE node with attr not working
我正在开发一个向 TinyMCE 添加按钮的 WordPress 插件,它允许您向所选元素添加一个 id 属性。我有按钮显示,当它被点击时它运行我的函数,我将调用 "idFunc" 这个演示,它看起来像这样:
function idFunc() {
// Make sure editor has focus.
editor.focus();
// Get currently selected node
var selectednode = editor.selection.getNode();
// Set the id attribute on the node
selectednode.attr("id","newid");
}
用上面写的 idFunc() ,当我点击我的按钮时没有任何反应。如果我将最后一行更改为这样的警报:
function idFunc() {
editor.focus();
var selectednode = editor.selection.getNode();
// Alert with the selected node
alert(selectednode);
}
我收到了预期的警报,其中显示:
The page at mytestingdomain.com says: [object HTMLParagraphElement]
如果我的插入符在 div 而不是 p 元素中,它会显示:
The page at mytestingdomain.com says: [object HTMLDivElement]
所以我知道我很接近,但是 attr()
函数没有向 TinyMCE 编辑器中的任何元素添加任何属性。
我做错了什么?
解决这个问题很简单。
editor.selection.getNode()
为您提供共同祖先节点(不是 jQuery 对象)。
要在节点上设置 id 属性,您可以调用以下命令之一:
selectednode.setAttribute("id","newid");
或
selectednode.id = "newid";
或使用jQuery
$(selectednode).attr("id","newid");
我正在开发一个向 TinyMCE 添加按钮的 WordPress 插件,它允许您向所选元素添加一个 id 属性。我有按钮显示,当它被点击时它运行我的函数,我将调用 "idFunc" 这个演示,它看起来像这样:
function idFunc() {
// Make sure editor has focus.
editor.focus();
// Get currently selected node
var selectednode = editor.selection.getNode();
// Set the id attribute on the node
selectednode.attr("id","newid");
}
用上面写的 idFunc() ,当我点击我的按钮时没有任何反应。如果我将最后一行更改为这样的警报:
function idFunc() {
editor.focus();
var selectednode = editor.selection.getNode();
// Alert with the selected node
alert(selectednode);
}
我收到了预期的警报,其中显示:
The page at mytestingdomain.com says: [object HTMLParagraphElement]
如果我的插入符在 div 而不是 p 元素中,它会显示:
The page at mytestingdomain.com says: [object HTMLDivElement]
所以我知道我很接近,但是 attr()
函数没有向 TinyMCE 编辑器中的任何元素添加任何属性。
我做错了什么?
解决这个问题很简单。
editor.selection.getNode()
为您提供共同祖先节点(不是 jQuery 对象)。
要在节点上设置 id 属性,您可以调用以下命令之一:
selectednode.setAttribute("id","newid");
或
selectednode.id = "newid";
或使用jQuery
$(selectednode).attr("id","newid");