2012-08-24 90 views
1
function toText() 
{ 
    var convertHTML =$('#mainContent').html(); 
    var ele = $(convertHTML + " > span").each(function(){ 
     $(this).replaceWith($(this).text()); 
    }); 
    console.log(ele); 


} 

我的目標是替換以下內容替換HTML使用jQuery

<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

這就是爲什麼我不能只使用文本(),因爲它需要還有<br>

回答

1

你服用返回的HTML字符串從$("#mainContent").html(),並試圖在真正需要的選擇是"#mainContent > span"使用它作爲下一行選擇的一部分。

試試這個:

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

你並不需要一個.each()循環:如果你通過一個函數來.replaceWith()該功能爲您的jQuery對象中的每個元素調用一次,你的回報值用作替換當前元素。

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

+0

完美答案+1 – LmC

3

試試這樣說:

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

你在哪裏使用HTML的整個塊作爲一個jQuery選擇:)

1

convertHTMLvar convertHTML =$('#mainContent').html();不是一個jQuery對象

你將不得不寫

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

原因:

$('#mainContent').html();將返回您不是一個jQuery對象$.each工作。

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

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