javascript 使用 jQuery 操作 TinyMCE 内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8828418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manipulating TinyMCE content with jQuery
提问by supertrue
With TinyMCE, I can easily manipulate content and send it back to the editor, like this:
使用 TinyMCE,我可以轻松操作内容并将其发送回编辑器,如下所示:
// get content from tinyMCE
var content = tinyMCE.get('content').getContent();
// manipulate content using js replace
content = content.replace(/<\/?div>/gi, '');
// send back to tinyMCE
tinyMCE.get('content').setContent( content );
The above code works fine. However, I can't get this to work:
上面的代码工作正常。但是,我无法使其正常工作:
// get content from tinyMCE (it provides an html string)
var content = tinyMCE.get('content').getContent();
// make it into a jQuery object
var $content = $(content);
// manipulate the jquery object using jquery
$content = $content.remove('a');
// use a chained function to get its outerHTML
content = $("<div />").append( $content.clone() ).html();
// send back to tinyMCE
tinyMCE.get('content').setContent( content );
Is there something wrong with my methodology?
我的方法有问题吗?
采纳答案by supertrue
The setting and getting to TinyMCE was correct; the problem was with my use of .remove()
:
设置和进入 TinyMCE 是正确的;问题在于我的使用.remove()
:
$content = $content.remove('a');
Since the content from TinyMCE was a single object, and nota collection of objects some of which were <a>
tags, that manipulation had no effect, and the html that returned was the same as the original.
由于 TinyMCE 的内容是单个对象,而不是对象的集合,其中一些是<a>
标签,因此该操作无效,并且返回的 html 与原始对象相同。
In order to remove links, I instead needed this:
为了删除链接,我需要这个:
$content = $content.find('a').remove();
I received clarification in this thread: Difference between $('#foo').remove('a') and $('#foo').find('a').remove()
我在这个线程中得到了澄清:Difference between $('#foo').remove('a') and $('#foo').find('a').remove()
回答by Thariama
You need to get the editor content using
您需要使用
var content = $('#content').html();
and set the content using
并使用设置内容
var content = $('#content').html('<span>NEW CONTENT</span>');