使用jQuery遍历html表

我是jQuery初学者试图使用jQuery遍历一个html表。 我经历了与此相关的各种post,但没有一个能满足我的问题陈述。

以下是示例html表:

..
ABC DEF

理想情况下,我希望形成一个字符串,其中包含由管道分隔的记录的所有单元格值:mytext,ABC | mytext2,DEF

尝试以下jQuery函数但无法实现此目的

 $(function abc() { $("#save").click( function() { var dataList; var recordList; var i = 0; $('#summaryTable tr').each(function() { alert('tr found'); $(this).find('td').each (function() { alert('td found'); var data = $(this).html(); }); }); }); }); 

任何帮助都会很棒。谢谢。

将post

根据你的问题和例子,trs具有相同的结构,

那么你需要的是这样的:

这是你想要“textfield value”,“selected value”| “下一个……”: JSFiddle

JS代码:

 var wordVal=""; var totalString = ""; $('#btn').click(function(){ totalString=""; $('table tr').each(function(i){ $(this).children('td').each(function(j){ if(j==0) wordVal = $(this).children('input').val().trim(); else totalString+= wordVal+','+$(this).children('select').val()+'|'; }); }); totalString= totalString.substring(0,totalString.length-1); console.log(totalString); }); 

(“textfield value”1,“option1”|“textField value”2,“option2”等)的js代码: JSFiddle

 var wordVal=""; var totalString = ""; $('#btn').click(function(){ totalString = ""; $('table tr').each(function(i){ $(this).children('td').each(function(j){ if(j==0) wordVal = $(this).children('input').val().trim(); $(this).children('select').children('option').each(function(k){ totalString+= wordVal+(k+1)+','+$(this).html()+'|'; }); }); totalString= totalString.substring(0,totalString.length-1)+'\n'; }); console.log(totalString); }); 

我仍然没有得到逗号和管道,但试试

 var objs = []; $("table :input").each(function(i, v) { objs.push($(v).val()); }); $("#result").html(objs.join("|")); 

这是小提琴 。

愿你自己解决这个问题。

     
 var NewString = ""; $(".nav li > a").each(function(){ NewString = NewString + "This,"+$(this).text()+"|"; }); 

算法:

 $(function () { $('button').click(function () { alert(getString()); }); function getString() { var rows = $('table>tbody>tr'); // all browsers always create the tbody element in DOM var arr = []; for (var i = 0; i < rows.length; i++) { var cells = rows.eq(i).children('td'); var text1 = cells.eq(0).find('input').val(); var text2 = cells.eq(1).find('select').val(); //var text2 = cells.eq(1).find('select option:selected').html();//alternative, if you want to collect the inner html instead arr.push(text1 + ',' + text2); // add string to array } return arr.join('|'); // join the string in array to single string } }); 

http://jsfiddle.net/T9RtQ/2/