清除样式属性中的HTML代码

问题描述:

我有一个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); 
    } 
}); 

任何想法?谢谢!

$("#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

removeAttr() should work fine for this purpose

我怀疑问题是您的选择器 - #post_content不在您提供的示例HTML中。