使用 jQuery 替换 HTML

Replace HTML Using jQuery

本文关键字:HTML 替换 jQuery 使用      更新时间:2023-09-26
function toText()
{
    var convertHTML =$('#mainContent').html();
    var ele = $(convertHTML + " > span").each(function(){
        $(this).replaceWith($(this).text());
    });
    console.log(ele);

}

我的目标是替换以下内容

    <div id="mainContent">
    test
<br>
    1234
<br>
    <span class="underline">test</span>
<br>
    <span class="underline">1234</span>
    </div>

并希望我的函数输出测试<br> 1234 <br> test <br> 1234

这就是为什么我不能只使用 text(( 因为它也带走了<br>

像这样尝试:

function toText()
{
    var ele = $("#mainContent > span").each(function(){
        $(this).replaceWith($(this).text());
    });
    console.log(ele);
}   

你在哪里使用整个 html 块作为 jQuery 选择器:)

您正在获取从$("#mainContent").html()返回的 html 字符串并尝试将其用作下一行选择器的一部分,而实际上您需要的选择器是"#mainContent > span" .

试试这个:

function toText()
{
    $("#mainContent > span").replaceWith(function(){ return $(this).text(); });
}

你不需要.each()循环:如果你传递一个函数来.replaceWith()那么对于jQuery对象中的每个元素,该函数被调用一次,并且你的返回值被用作当前元素的替换。

演示:http://jsfiddle.net/7xKzP/

来自 var convertHTML =$('#mainContent').html();convertHTML不是 jQuery 对象

你将不得不写

var ele = $("#mainContent > span").each(function(){
        $(this).replaceWith($(this).text());
    });

原因:

$('#mainContent').html();将返回string而不是 jQuery 对象,供$.each工作。

var ele = $(convertHTML + " > span")意味着

var ele = $("test<br>1234<br><span class="underline">test</span><br><span class="underline">1234</span>" + " > span")