【问题标题】:How do I change this HTML into a table using jQuery如何使用 jQuery 将此 HTML 更改为表格
【发布时间】:2011-12-06 22:29:04
【问题描述】:

我有一些任意文本,我想将它们转换成带有一些值的表格。我不知道这是否可能。 HTML如下:

<div class="custom_meta">
    <strong>Length: </strong>
    11.22.33.44.55.66
    <br>

    <strong>Width: </strong>
    11.22.33.44.55.66
    <br>
</div>

我想将输出更改为:

<div class="custom_meta">
    <table>
        <tbody>
            <tr>
                <td>
                    <strong>Length: </strong>
                </td>
                <td>11</td>
                <td>22</td>
                <td>33</td>
                <td>44</td>
                <td>55</td>
                <td>66</td>
            </tr>

            <tr>
                <td>
                    <strong>Width: </strong>
                </td>
                <td>11</td>
                <td>22</td>
                <td>33</td>
                <td>44</td>
                <td>55</td>
                <td>66</td>
            </tr>
        </tbody>
    </table>
</div>

说来话长,但我找不到任何插件来简单地将自定义字段转换为 wp 电子商务中的表格。我尝试的第一段代码很不及格。我想通过使用 .before() 函数插入 HTML 表的开头位开始,但它最终关闭了标签,然后我可以自己在关闭 div 的末尾关闭它。即,

$(".custom_meta strong:first").before("<table><tbody><tr><td>");

在第一个强标签之前打开和关闭标签。

【问题讨论】:

  • 您是否无权访问后端以简单地正确输出它开始?
  • 顺便说一句,您可能应该使用&lt;th&gt; 而不是那些&lt;td&gt;&lt;strong&gt;
  • @herby:你不应该在&lt;thead&gt; 中只有&lt;th&gt; 标签吗?
  • 必须承认,不确切知道,但我会说不。您也可以在列中使用标题,而不仅仅是在行中。
  • @Rocket - 编号th 可以在一行或一列中;实际上,th 元素有一个 scope 属性,您可以使用它明确指出 th 是否适用于行或列。见developer.mozilla.org/en/HTML/Element/th

标签: jquery html wordpress e-commerce


【解决方案1】:

您可以使用contents() 查找所有节点,并编写自定义过滤器以仅查找包含. 的文本节点,并将其用作数据值的来源。

这样的事情会起作用:

var headers = $('.custom_meta strong');
var values = $('.custom_meta').contents().filter(function() {
    return this.nodeType == 3  // text node
        && this.nodeValue.indexOf('.') > 0;
});

var table = $('<table/>');
var tbody = $('<tbody/>');

headers.each(function(n) {
    var tr = $('<tr/>');
    tr.append($('<td><strong>' + $(this).html() + '</strong></td>'));

    var itemValues = values[n].nodeValue.split('.');
    for(var i = 0; i < itemValues.length; i++) {
        tr.append($('<td>' + itemValues[i].trim() + '</td>'));
    }

    tbody.append(tr);
});

table.append(tbody);
$('.custom_meta').empty().append(table);

Demo

【讨论】:

    【解决方案2】:

    类似:

    $html = $(".custom_meta").html(); //store original value
    $(".custom_meta").html("<table><tbody id='mytbody'></tbody></table>"); //set html to nothing
    var rows = $html.split("<br>"); //split the html based on <br>
    for(var i = 0; i < rows.length - 1; i++) { //loop until i = length - 1 (- 1 because there are as many <br> tags as <strong> tags - so there would be one before and after each <br>, thus you want to get rid of the last one.
        $("#mytbody").append("<tr><th>" + $("<div></div>").html($html).find("strong:eq(" + i + ")").html() + "</th></tr>"); //create a new div temporarily, add the original html and then get the content of the strong at the current position (i)
    }
    

    这至少应该让您入门 - 但是,我不会给您完整的答案,因为您不一定会那样学习。剩下的就是提取 . 分隔的列表,然后根据 .. 拆分列表。

    问候, 理查德

    编辑:看我的 JS 小提琴 - http://jsfiddle.net/a6Bcu/

    【讨论】:

    • 感谢 cmets 解释代码。即使问题得到了充分的回答,我也会仔细阅读,以便真正从中学习。
    【解决方案3】:

    这可能不是最干净的解决方案,但它至少可以工作:

    function nextSiblingToCells(that){
        var t = that.nextSibling.nodeValue.split('.');
        for (i=0;i<t.length;i++){
            $('<td />').text(t[i]).appendTo($('table tbody tr:last'));
        }
    };
    
    var table = document.createElement('table'),
        tbody = document.createElement('tbody'),
        text;
    
    table.appendChild(tbody);
    
    $(table).appendTo($('.custom_meta:first'));
    
    $('strong').each(
        function(){
            text = $(this).text();
            $('<tr />').appendTo($(table)).append('<td>' + text + '</td>');
            nextSiblingToCells(this,'br');
        });
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

      【解决方案4】:

      以下应该有效:

      var table = $('<tbody></tbody>');
      $('.custom_meta').contents().filter(function() {
        return this.nodeType === 3;
      }).each(function() {
        var row = $('<tr></tr>');
        var header = $(this).prevAll('strong');
        if (header.length) {
          row.append($('<td></td>').append(header));
          $.each($(this).text().split('.'), function(index, element) {
              row.append($('<td>' + element + '</td>'));
          });
          table.append(row);
        }
      });
      $('.custom_meta').empty().append($('<table></table>').append(table));
      

      See here for jsFiddle.

      【讨论】:

        【解决方案5】:
        final_contents = "<table>"; 
        
        $('.custom_meta').contents().each(function(){ 
             var values = []; 
            if( $(this).text().trim() === 'Length:' )
             {
                 final_contents += "<tr>";
                 final_contents += "<td>Length:</td>";   
             }
            else if( $(this).text().trim() === 'Width:' )
            {
                 final_contents += "<tr>";
                 final_contents += "<td>Width:</td>"; 
            } 
        
             if( this.nodeType === 3 && $(this).text().trim().length !== 0 )
                 values = $(this).text().split('.'); 
        
             for( var i = 0; i < values.length; i++ ) 
                  final_contents += "<td>"+values[i].trim() + "</td>"; 
        
             if( this.nodeName.trim() === 'BR' )
                 final_contents += "</tr>"  
        })
        
        final_contents += "</table>";     
        $('.custom_meta').html( final_contents ); 
        

        这是fiddle

        【讨论】:

          【解决方案6】:

          这是另一个实现。老实说,其中大多数都可以正常工作。

          此实现的缺点是假设&lt;br&gt; 将始终分隔行,&lt;strong&gt; 将始终包含标题信息:http://jsfiddle.net/rkw79/DAwuw/4/

          var nodes = $.map($('.custom_meta:first').html().split('<br>'), function(o, i) {
              return $.trim(o);
          });
          
          var rows = $.map(nodes, function(row) {
              if (row == '') { return ''; }
              row = row.replace('</strong>', '</strong>.');
              tds = $.map(row.split('.'), function(td) { return '<td>' + td + '</td>'; }).join('\n');
              return '<tr>' + tds + '</tr>';
          }).join('\n');
          
          $('body').append($('<table></table>').append(rows));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-06-11
            • 2017-04-26
            • 2010-10-09
            • 1970-01-01
            • 1970-01-01
            • 2013-05-07
            • 1970-01-01
            • 2011-10-02
            相关资源
            最近更新 更多