从html表中提取数据并使用jQuery构建字符串

时间:2013-08-22 18:29:07

标签: jquery html-table

我有以下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中有任何方法/函数可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

我建议:

// 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

更新了上述内容以包含代字号(~):

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

参考文献:

答案 1 :(得分: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