![](/img/trans.png)
[英]Select a row from html table and select multiple rows using javascript without jquery
[英]Select multiple rows from html table and send values to a function in javascript
我有一个HTML表,需要在其中选择多行并将每行的第一个单元格值发送给函数。 我尝试了下面的代码。 这仅选择一行,并且仅向该函数发送一个值。 如果我选择多行,则只有第一个选择的值正在输入该函数。 我该如何解决这个问题?
的test.html
<table id="table">
<tr>
<td>1 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>
</tr>
<tr>
<td>2 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>
</tr>
<tr>
<td>3 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>
</tr>
</table>
<input type="button" class="ok" id="tst" value="OK" onclick="" />
test.js
$("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
var selectedID=$("#table tr.selected td:first").html();
fnMatchID(selectedID);
});
function fnMatchID(selectID){
//some code here
}
演示:::: JSFiddle
我需要选择多行并将所选行的所有第一个单元格值发送给一个函数。
根据您是要多次调用该函数还是将数据作为数组发送,您可以做两件事。
无论哪种方式,如果您希望能够选择多行,都不要在.siblings()上移除removeClass。 如果您希望能够取消选择行,则还可以考虑使用.toggleClass(“ selected”)而不是.addClass(“ selected”)。
解决方案1:将数据作为字符串数组发送
$("#table tr").click(function(){
$(this).addClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
var selectedIDs = [];
$("#table tr.selected").each(function(index, row) {
selectedIDs.push($(row).find("td:first").html());
});
fnMatchID(selectedIDs);
});
解决方案2:反复调用功能
$("#table tr").click(function(){
$(this).addClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
$("#table tr.selected").each(function(index, row) {
fnMatchID($(row).find("td:first").html());
});
});
无论哪种方式,您可能都在寻找.each函数: http ://api.jquery.com/each/
简单的解决方案就是这样,
$("#table tr").click(function(){
$(this).toggleClass('selected');
});
$('.ok').on('click', function(e){
var selected = [];
$("#table tr.selected").each(function(){
selected.push($('td:first', this).html());
});
alert(selected);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.