【问题标题】:Select multiple rows from html table and send values to a function in javascript从html表中选择多行并将值发送到javascript中的函数
【发布时间】:2014-07-17 06:22:12
【问题描述】:

我有一个 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

我需要选择多行并将所选行的所有第一个单元格值发送到一个函数。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    根据您是要多次调用函数还是将数据作为数组发送,您可以做两件事。

    无论哪种方式,如果您希望能够选择多行,请不要删除 .siblings() 上的类。如果您希望能够取消选择行,您也可以考虑使用 .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);
    
    });
    

    方案二:反复调用函数

    $("#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/

    【讨论】:

      【解决方案2】:

      简单的解决方案是这样的,

      $("#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);
      });
      

      UPDATED FIDDLE

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多