【问题标题】:How to "unwrap" tags? [duplicate]如何“解开”标签? [复制]
【发布时间】:2009-11-26 09:06:08
【问题描述】:

我有这段 HTML 代码:

<center><table><tr><td>table</td></tr></table></center>

我如何从&lt;center&gt;解开表格

对不起,我什至不知道如何开始。

非常感谢

【问题讨论】:

  • 我不确定你的问题是什么?
  • “解包”是什么意思?提取文本?
  • 您的意思是删除&lt;center&gt; 标签,保留子内容完整吗?
  • 你想要的最终结果是什么?

标签: jquery


【解决方案1】:

我宁愿完全摆脱中心标签或用一些 div 替换它。中心标签没有包裹在任何东西中。有什么想法吗?

它没有包裹在任何东西中?然后把它包起来,当然!

var $center = $('center');
var $newReplacement = $("<div></div>");

$center.wrap($newReplacement);
$newReplacement.html($center.html());

或者:

var $center = $("center");
$("<div></div>")
    .insertBefore($center)
    .html($center.html())
;
$center.remove();

再一次,但这次没有丢失事件:

var $contents = $("center > *")
    .clone(true)   // not sure if this is needed
    .appendTo(
         $("<div></div>").insertBefore("center")
    )
;
$("center").remove();

【讨论】:

  • 我更喜欢第二个——但您不需要将新的 DIV 分配给变量。
  • 通过使用 html() 你会丢失事件等。
【解决方案2】:
var $table = $("center table");
var $center = $table.parent();
$table.insertBefore($center);
$center.remove();

【讨论】:

  • 此解决方案比更改 html 或克隆 nickf 之类的东西要快得多
【解决方案3】:

这个功能很好用;

jQuery.fn.unwrap = function (el) {
    return this.each( function(){
      $(this.childNodes).appendTo(this.parentNode );
    });
};

【讨论】:

    【解决方案4】:

    为了避免一个新的变量或函数,我通常会这样“解包”:

        $("center").each(function(){
           $(this).replaceWith($(this).html());
        });
    

    我使用匿名函数调用 .each 来获取 $(this) 的句柄

    在您的情况下,如果您的页面上有多个中心标签,您还需要使用 id 属性标记要删除的标签,并使用以下内容选择它:

    $("#zapthis").each(...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2019-10-29
      • 2015-06-05
      • 2012-03-11
      • 1970-01-01
      • 2021-10-05
      • 2018-05-20
      相关资源
      最近更新 更多