繁体   English   中英

将HTML标签替换为另一个标签,然后删除其他标签

[英]Replace html tag with another tag and then remove other tags

我有一个textarea ,用户可以在其中编辑一些文本,允许他们使用html(我知道所有用户并信任他们),然后将该textarea的内容保存在数据库中。 然后将printet放入元素中。

如何使用<b>标签替换所有标题<h1><h2><h3>等,然后删除与<b><p>不同的所有标签

用户输入将存储在这样的变量中:

column_content = $('.dialog_editor').val();

尝试

$('.dialog_editor').change(function () {
    var column_content = $('.dialog_editor').val();

    var $temp = $('<div />',{html: column_content});

    //process headers
    $temp.find(':header').wrapInner('<b />').contents().unwrap();

    $temp.find('*:not(p, b)').contents().unwrap();

    $('#html').html($temp.html());
    $('#text').text($temp.html());
});

演示: 小提琴

这应该使您开始:

var column_content =
    '<h1>Test 1</h1>\n' +
    '<p>Lorem Ipsum</p>\n' +
    '<h2>Test 2</h2>\n' +
    '<input type="button" onclick="alert(&quot;missed me&quot;)" value="Click">\n' +
    '<a href="javascript://">keep this</a>\n' +
    '<h3>Test 3</h3>\n' +
    'unwrapped text';

var $temp = $("<div></div>").html(column_content);

$temp.find("h1, h2, h3").each(function () {
    $(this).wrapInner("<b></b>").children().insertAfter(this);
});
$temp.find(":not(b, p)").each(function () {
    $(this).contents().insertAfter(this);
    $(this).remove();
});
console.log($temp.html());
/*
<b>Test 1</b>
<p>Lorem Ipsum</p>
<b>Test 2</b>

keep this
<b>Test 3</b>
unwrapped text
*/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM