【问题标题】:jquery get HTML of an element stripping the style attributejquery获取剥离样式属性的元素的HTML
【发布时间】:2012-04-20 18:50:41
【问题描述】:

是否可以获得元素的原始 HTML,或者是否可以获得没有“样式”属性的 HTML?考虑以下示例,

<div class="outer">
   <div class="inner">
       some text
   </div>
</div>

现在,我将一些动画/CSS 应用到“内部”元素。

​$('.inner').animate({
    'margin': '-10px'
});​​

当我使用console.log($('.outer').html()); 获取“外部”元素的 HTML 时,我得到以下内容

<div class="inner" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; ">
       some text
   </div>

但是,我实际上只需要这个

<div class="inner">
       some text
   </div>

获得该输出的最简单方法是什么?在应用 animate() 或 css() 之前,我不需要创建元素的备份。

谢谢。

【问题讨论】:

  • “当我得到“外部”元素的 HTML 时”。你怎么得到它?您可以发布您正在使用的代码吗?
  • 尝试$('.inner').removeAttr("style"); 删除样式

标签: javascript jquery html css jquery-animate


【解决方案1】:

如果您想完全删除样式属性(并且不希望它恢复),请使用以下代码:

/* Working code */ 
$(".outer").find(".inner").removeAttr('style').end().html();

/* Explanation of working code */
$(".outer")                     // Get the outer element
           .find(".inner")      // Find the inner div
           .removeAttr('style') // Remove the attribute from the inner div
           .end()               // Return to the outer div
           .html();             // Get outer div's HTML

这里是a working fiddle

jQuery 文档:

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    相关资源
    最近更新 更多