如何使用JQuery在嵌套HTML中提取文本?
我这里有HTML代码:
Order Number 1 Customer Number 3 Complaint Code b Receivable Receipt Number 5 Date Called 2014-03-19 Scheduled Day Of Checkup 2014-03-19 Scheduled Day Of Service 2014-03-21 Checkup Status Y Service Status N Technician Number Checkup 3 Technician Number Service 1
我想得到标签的值并将它们放入一个数组结构的数组中(“first td”=>“second td”),所以对于这种情况,数组就是数组(“Order Number”=> “1”,“客户编号”=>“3”,“投诉代码”=>“b”,……)依此类推。
之后,最终的数组将被发送到PHP代码中。
我一直在尝试使用var html = $(this).filter(function( index ){ return $("td", this) }).filter(":odd").text();
从HTML中提取一些值var html = $(this).filter(function( index ){ return $("td", this) }).filter(":odd").text();
和filter()的各种其他组合,但它似乎并不适合我。
我该怎么做我想做的事情?
jsFiddle Demo
您将要使用.each
并.each
代表中的行。 对于每一行,将第一个单元格( .eq(0)
)作为键,将第二个单元格( .eq(1)
)作为值。 将它们放在结果对象中。
//object to hold resulting data var result = {}; //iterate through rows $('.actResult tr').each(function(){ //get collection of cells var $tds = $(this).find('td'); //set the key in result to the first cell, and the value to the second cell result[$tds.eq(0).html()] = $tds.eq(1).text(); });
您可以获取表元素的rows
属性,并根据单元格的值创建一个对象:
var rows = document.querySelector('.actResult table').rows, data = {}, c, l = rows.length, i = 0; for (; i < l; i++) { c = rows[i].cells; data[c[0].innerHTML] = c[1].innerHTML; }