【问题标题】:Adding attribute to TinyMCE node with attr not working使用 attr 向 TinyMCE 节点添加属性不起作用
【发布时间】:2015-10-01 17:18:46
【问题描述】:

我正在开发一个 WordPress 插件,它向 TinyMCE 添加了一个按钮,它允许您向所选元素添加一个 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);

}

我按预期收到了一条警报,上面写着:

mytestingdomain.com 上的页面显示: [object HTMLParagraphElement]

如果我将插入符号放在 div 而不是 p 元素中,它会说:

mytestingdomain.com 上的页面显示: [object HTMLDivElement]

所以我知道我很接近了,但 attr() 函数没有向 TinyMCE 编辑器中的任何元素添加任何属性。

我做错了什么?

【问题讨论】:

    标签: wordpress tinymce


    【解决方案1】:

    解决这个问题很简单。 editor.selection.getNode() 为您提供公共祖先节点(不是 jQuery 对象)。

    要在节点上设置 id 属性,您可以调用以下命令之一:

    selectednode.setAttribute("id","newid");
    

    selectednode.id = "newid";
    

    或使用 jQuery

    $(selectednode).attr("id","newid");
    

    【讨论】:

    • 天哪,这很容易!我不知道我怎么从来没有尝试过这些组合。非常感谢!
    • @JoeRhoney:很高兴能够提供帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    相关资源
    最近更新 更多