0

我有以下 HTML 表格:

<tbody>
   <tr>
      <th>Actions</th><th>Contact Type</th><th>Contact</th><th>Call Order</th>  <th>Text</th>
   </tr>
   <tr id="rulesegment_1">
       <td><input type="button" value="Remove" class="removeruleset"></td>
       <td class="contact_type" id="contact_type1">6</td>
       <td id="contact_details1">1234</td>
       <td class="call_order" id="call_order1">1</td>
       <td class="textm" id="textm1">false</td>
    </tr>
    <tr id="rulesegment_2">
       <td><input type="button" value="Remove" class="removeruleset"></td>
       <td class="contact_type" id="contact_type2">4</td>
       <td id="contact_details2">123424234</td>
       <td class="call_order" id="call_order2">1</td>
       <td class="textm" id="textm2">false</td>
   </tr>
  </tbody>

我需要从表中提取所有数据并最终得到一个如下所示的字符串:

  "6,1234,1,false~4,123424234,1,false~"

最好的方法是什么?jQuery中是否有任何方法/函数可以做到这一点?

4

2 回答 2

1

I'd suggest:

// select all the 'td' elements:
var str = $('td').filter(function(){
    /* filter those elements to keep only those the
       length of whose trimmed text is greater than zero:
    */
    return $.trim($(this).text()).length > 0;
}).map(function(){
    // trim the text of those kept 'td' elements, and return it
    return $.trim($(this).text());
/* store it in an array (using 'get()'), and join those array
   elements together with commas:
/*
}).get().join(',');

console.log(str);

JS Fiddle demo.

Updated the above to include the tilde (~):

var str = $('td').filter(function(){
    return $.trim($(this).text()).length > 0;
}).map(function(){
    var self = $(this),
        text = self.text();
    return !self.next().length ? text + '~' : text;
}).get().join(',');

console.log(str);

JS Fiddle demo.

References:

于 2013-08-22T18:32:46.090 回答
0

只需链接您的 $.map 调用,用于处理行和单元格,如下所示:

// Get all the tr's that have an id attribute
$.map($('tr[id]'),function(node){

    // Inside of each row, exclude the cells that have an input.
    return $.map($('td', node).not(':has(input)'), function(td){
         return $(td).text();
    }).join(','); // Join the text with a comma
}).join('~'); // Join the rows with a tilde

这是测试:

http://jsbin.com/avUb/1/edit

于 2013-08-22T19:45:38.630 回答