【问题标题】:Replace element and preserve attributes替换元素并保留属性
【发布时间】:2013-12-04 00:58:46
【问题描述】:

以下几乎可以用lis替换span[data-type="yesno"]的所有实例,但我还想保留属性、类等。有没有办法以与html相同的方式继承属性?

$('span[data-type="yesno"]').replaceWith(function(){
    return $("<li>", {html: $(this).html()});
})

【问题讨论】:

  • 是的,但是您必须遍历您希望保留的每个属性并将其添加到您传递给$() 的属性列表中。
  • 我猜这会给你无效的 HTML 标记,或者我错了?!
  • @KevinB 这不是我在上面做的吗?似乎是这样,因为它保留了每个跨度的单个 html。
  • @A.Wolff 如果我将这些元素移动到 ul 中,对吧?
  • @jboneca 是子元素,但不是 span/li 上的属性。

标签: jquery dom replacewith


【解决方案1】:

你必须循环你的元素属性:

$('span[data-type="yesno"]').replaceWith(function(){
   $li = $("<li>", {html: $(this).html()});
   $.each(this.attributes, function(i, attribute){
        $li.attr(attribute.name, attribute.value);
  });
  return $li;
})

【讨论】:

  • 像我们所有人一样 ;) 如果适合您,请不要忘记将答案标记为已接受。好好学习!
  • 必须等待一段时间才能接受,干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
相关资源
最近更新 更多