修改标签<a> via jQuery each loop

时间:2018-10-27 04:13:59

标签: jquery

I'm trying to modify a series of tag in a string that is taken from a textarea (TinyMCE). I'd like to add data-toggle, data-hover and a class (only if there is a specific word in a the href attribute)

var elements = tinyMCE.get('text').getContent(); //retrieve the content from textarea
var results = [];
var links = [];
$(elements).html(elements).find("a").each(function(l) {
     $(this).attr("data-toggle", "popover");
     $(this).attr("data-trigger", "hover");
     $(this).addClass("classLink");

     results.push($(this).attr('href'));
     str = $(this).attr('data-toggle') + "--" + $(this).attr('data-trigger') + "---" + $(this).attr('class');
     links.push(str);

 });
 console.log(results);
 console.log(links);

Now the two arrays printed in the console show the right content. The problem is that I'd like to update the string elements and update the content in the textarea.

And after many attempt by using the alert() function nothing works. Any idea? Thanks a lot

1 个答案:

答案 0 :(得分:2)

您正在获取一个字符串,从中创建html元素,修改这些元素,但您没有将这些元素推回字符串中

var elements = tinymce.activeEditor.getContent()

var $elements = $('<div>' + elements + '</div>');
$elements.find("a").each(function() {
     $(this).addClass("classLink");
     });

elements = $elements.html();
tinyMCE.activeEditor.setContent(elements)
alert(elements)

我刚刚通过http://fiddle.tinymce.com/进行了尝试,并且似乎可以正常工作,tinymce中的内容已更新

http://fiddle.tinymce.com/R2gaab