簡體   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