【问题标题】:jQuery/javascript replace tag typejQuery/javascript 替换标签类型
【发布时间】:2010-05-12 01:52:10
【问题描述】:

有没有一种简单的方法可以遍历所有 td 标签并将它们更改为 th? (等等)。

我目前的方法是用 th 包装它们,然后删除 td,但随后我会丢失其他属性等。

【问题讨论】:

  • 您想维护<td>上当前的属性?
  • 是的。我想维护他们的一切。
  • 有什么原因不能在服务器上完成吗?这不是在客户端上轻松完成的,至少不是为了处理所有可能的情况,元素的标签类型一旦添加到 DOM 中是不可变的。
  • 您可能需要考虑一个替代的默认 DOM 结构来实现您想要实现的任何效果。您的操作可以完成,但正如尼克所说,这不是一项简单的任务,特别是如果您的 td 标签数量可以是可变数量。

标签: javascript jquery tagname


【解决方案1】:

jQuery.replaceTagName

下面是一个替换DOM元素标签名的jQuery插件。

来源

(function($) {
    $.fn.replaceTagName = function(replaceWith) {
        var tags = [],
            i    = this.length;
        while (i--) {
            var newElement = document.createElement(replaceWith),
                thisi      = this[i],
                thisia     = thisi.attributes;
            for (var a = thisia.length - 1; a >= 0; a--) {
                var attrib = thisia[a];
                newElement.setAttribute(attrib.name, attrib.value);
            };
            newElement.innerHTML = thisi.innerHTML;
            $(thisi).after(newElement).remove();
            tags[i] = newElement;
        }
        return $(tags);
    };
})(window.jQuery);

缩小来源

(function(e){e.fn.replaceTagName=function(t){var n=[],r=this.length;while(r--){var i=document.createElement(t),s=this[r],o=s.attributes;for(var u=o.length-1;u>=0;u--){var a=o[u];i.setAttribute(a.name,a.value)}i.innerHTML=s.innerHTML;e(s).after(i).remove();n[r]=i}return e(n)}})(window.jQuery);

用法

在 jQuery 之后的 javascript 中包含上述缩小的源代码。

然后你可以像这样使用插件:

$('div').replaceTagName('span'); // replace all divs with spans

或者在你的情况下:

$('td').replaceTagName('th');

jQuery 选择器按预期工作

$('.replace_us').replaceTagName('span'); // replace all elements with "replace_us" class with spans
$('#replace_me').replaceTagName('div'); // replace the element with the id "replace_me"

更多资源

jsFiddle with Qunit tests

【讨论】:

    【解决方案2】:

    完全未经测试,但试一试:

    $("td").each(function(index) {
      var thisTD = this;
      var newElement = $("<th></th>");
      $.each(this.attributes, function(index) {
        $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
      });
      $(this).after(newElement).remove();
    });
    

    我一直在看着它,我想不出它不起作用的原因!

    1) 循环遍历每个 td 元素
    2) 创建一个新的 th 元素
    3) 对于每个 td,循环遍历其每个属性
    4) 将该属性和值添加到新的 th 元素
    5)一旦所有属性都到位,在 td 之后立即将元素添加到 DOM,并删除 td

    编辑: 工作正常:http://jsbin.com/uqofu3/edit

    【讨论】:

    • 效果很好!如果你想复制元素内部 html 你可以添加这个 $(newElement).html($(this).html());在最后一行之前。
    【解决方案3】:
    $("td").each(function() {
      var tmp = $('<div/>').append($(this).clone(true)).html().replace(/td/i,'th');
      $(this).after(tmp).remove();
    });
    

    或纯 DOM

    function replaceElm(oldTagName, newTagName, targetElm) {
      var target = targetElm || window.document;
      var allFound = target.getElementsByTagName(oldTagName);
      for (var i=0; i<allFound.length; i++) {
        var tmp = document.createElement(newTagName);
        for (var k=0; k<allFound[i].attributes.length; k++) {
          var name = allFound[i].attributes[k].name;
          var val = allFound[i].attributes[k].value;
          tmp.setAttribute(name,val);
        }
        tmp.innerHTML = allFound[i].innerHTML;
        allFound[i].parentNode.insertBefore(tmp, allFound[i]);
        allFound[i].parentNode.removeChild(allFound[i]);
      }
    }
    
    replaceElm('td','th',document.getElementsByTagName('table')[0]);
    

    DOM 总是更快:http://jsperf.com/replace-tag-names

    【讨论】:

    • 在您的 jQuery 解决方案中,正则表达式将应用于整个 html 内容,这可能会产生意想不到的结果。
    【解决方案4】:

    这可能有效,但我尚未对其进行广泛测试:

    var tds = document.getElementsByTagName("td");
    while(tds[0]){
        var t = document.createElement("th");
        var a = tds[0].attributes;
        for(var i=0;i<a.length;i++) t.setAttribute(a[i].nodeName,a[i].nodeValue);
        t.innerHTML = tds[0].innerHTML;
        tds[0].parentNode.insertBefore(t,tds[0]);
        tds[0].parentNode.removeChild(tds[0]);
    }
    

    我希望它在某些方面有所帮助。

    【讨论】:

      【解决方案5】:

      对@GlenCrawford 的回答稍加补充,以保留带有该行的内部文本:

      newElement.text($(value).text());
      

      现在大家一起:

      $("td").each(function(index) {
        var thisTD = this;
        var newElement = $("<th></th>");
        newElement.text($(value).text());
        $.each(this.attributes, function(index) {
          $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
        });
        $(this).after(newElement).remove();
      });
      

      【讨论】:

        【解决方案6】:

        好吧,这个问题已经很老了,但这无论如何都会有所帮助:唯一真正按预期工作的 jQuery 插件(你不能在另一个中重用返回的对象,例如添加属性):

        jQuery.fn.extend({
            replaceTagName: function(replaceWith) {
                var tags=[];
                this.each(function(i,oldTag) {
                    var $oldTag=$(oldTag);
                    var $newTag=$($("<div />").append($oldTag.clone(true)).html().replace(new RegExp("^<"+$oldTag.prop("tagName"),"i"),"<"+replaceWith));
                    $oldTag.after($newTag).remove();
                    tags.push($newTag.get(0));
                });
        
                return $(tags);
            }
        });
        

        除了基本的$("td").replaceTagName("th");,你还可以像$("td").replaceTagName("th").attr("title","test");这样链接调用

        缩小版:

        jQuery.fn.extend({replaceTagName:function(a){var b=[];this.each(function(d,c){var e=$(c);var f=$($("<div />").append(e.clone(true)).html().replace(new RegExp("^<"+e.prop("tagName"),"i"),"<"+a));e.after(f).remove();b.push(f.get(0))});return $(b)}});
        

        【讨论】:

          【解决方案7】:

          这比@GlenCrawford 的回答更简洁,并且还复制了被替换元素的子元素。

          $('td').each(function(){
              var newElem = $('<th></th>', {html: $(this).html()});
              $.each(this.attributes, function() {
                  newElem.attr(this.name, this.value);
              });
              $(this).replaceWith(newElem);
          });
          

          【讨论】:

          • 在提出问题(已被接受)4年后发布另一个答案是没有用的。
          • 虽然此源代码可以提供答案,但几句话的解释将使当前和未来的读者受益。
          • 添加了一些解释。
          猜你喜欢
          • 2013-09-06
          • 1970-01-01
          • 2013-12-07
          • 2011-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多