2013-02-12 51 views
2

我有一個contenteditable,並且可以選擇複製用戶文本的HTML代碼。我想刪除由瀏覽器添加到某些元素的style=""屬性。例如:清除樣式屬性中的HTML代碼

<h2>what</h2><p><span style="color: rgb(54, 54, 54); font-size: 18px; line-height: 1.77777778em;">what is&nbsp;this</span><span style="color: rgb(54, 54, 54); font-size: 18px; line-height: 1.77777778em;">&nbsp;</span></p><p></p> 

我該怎麼用jQuery做到這一點?

我試過,但它不工作:

$('#post_content').keydown(function(e) { 
    // if ctrl + e 
    if ((e.metaKey || e.ctrlKey) && e.keyCode == 69) { 
    var html = $('#post_content').removeAttr('style').html(); 
    prompt("Ctrl+C to copy HTML code", html); 
    } 
}); 

任何想法?謝謝!

回答

2
$("#post_content *").removeAttr("style"); 
prompt("Ctrl+C to copy HTML code", $("#post_content").html()); 

http://jsfiddle.net/WHRST/

你必須選擇所有CONTENTEDITABLE元素的後代。所以你在select中使用(*),一旦你擁有所有後代,你可以調用.removeAttr(「style」),它將從集合中的每個元素中移除。

+0

謝謝,它效果很好! – Alex 2013-02-12 20:26:57

+0

後續問題:我可以這樣做嗎(將HTML元素存儲在var中並調用以從該var中刪除屬性)? (目前不工作): 'var select = getHTMLOfSelection(); select = select.removeAttr('style');' – Alex 2013-02-12 21:06:58

+0

@Alex - jQuery結果是jQuery對象的集合(列表)。這些對象代表jQuery增強的HTML DOM元素。你不能只取HTML字符串值並嘗試在其上調用jQuery函數。 – 2013-02-13 12:10:06