Wordpress 向TinyMCE节点添加属性时attr不起作用
我正在开发一个WordPress插件,它在TinyMCE中添加了一个按钮,允许您向所选元素添加一个id属性。我有一个按钮显示,当它被点击时,它运行我的函数,我将为这个演示调用“idFunc”,它看起来像这样:Wordpress 向TinyMCE节点添加属性时attr不起作用,wordpress,tinymce,Wordpress,Tinymce,我正在开发一个WordPress插件,它在TinyMCE中添加了一个按钮,允许您向所选元素添加一个id属性。我有一个按钮显示,当它被点击时,它运行我的函数,我将为这个演示调用“idFunc”,它看起来像这样: function idFunc() { // Make sure editor has focus. editor.focus(); // Get currently selected node var selectednode = editor.selection.g
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");
}
function idFunc() {
editor.focus();
var selectednode = editor.selection.getNode();
// Alert with the selected node
alert(selectednode);
}
对于如上所述编写的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");
}
function idFunc() {
editor.focus();
var selectednode = editor.selection.getNode();
// Alert with the selected node
alert(selectednode);
}
我收到了一个预期的警报,上面写着:
mytestingdomain.com上的页面上写着:[object HTMLParagraphElement]
如果我把插入符号放在div而不是p元素中,它会说:
mytestingdomain.com的页面上写着:[object HtmlLevel]
所以我知道我很接近了,但是attr()
函数没有向TinyMCE编辑器中的任何元素添加任何属性
我做错了什么?解决这个问题很简单。
editor.selection.getNode()
提供公共祖先节点(不是jQuery对象)
要在节点上设置id属性,可以调用以下命令之一:
selectednode.setAttribute("id","newid");
或
或者使用jQuery
$(selectednode).attr("id","newid");
天哪,那很容易!我不知道我怎么从来没有试过这些组合。非常感谢你@乔霍尼:很高兴能帮上忙:)