【问题标题】:Getting the value of the selected row and column in the table using JQuery使用JQuery获取表格中选定行和列的值
【发布时间】:2017-08-09 00:40:10
【问题描述】:

我正在尝试使用每个单元格中的按钮获取所选行的列的值。这是我的 Jquery,

$('.sampleBtn').click(function(){
  var row = $(this).closest('td');
  var col = $(this).parent().children().index($(this));
  var id = row.find('.mainId').val();
  var level = row.find('.level').val();

  alert("Main ID "+id+" Job ID "+col+" Level "+level);
});

当我使用可点击的单元格时它可以正常工作,但是当我使用按钮时,即使我点击其他单元格中的按钮,它总是说我在第 3 列。

视图中表格的主体,

 <?php foreach($mains as $temp): ?>
<tbody>
  <tr>
    <td>
      <input type="hidden" value="<?php echo $temp->Main_ID; ?>"/><?php echo $temp->Main_Name; ?>
    </td>
    <td>
      <select class="level">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
      </select>
      <input type="hidden" class="mainId" value="<?php echo $temp->Main_ID; ?>" />
      <input type="button" class="sampleBtn" value="Update" />
    </td>
  </tr>
</tbody>
<?php endforeach; ?>

【问题讨论】:

    标签: php jquery html-table


    【解决方案1】:

    那是因为您在更改触发的 DOM 元素后没有更新 $(this) 引用。按钮的this 范围是&lt;input&gt; 元素,对于单元格它是&lt;td&gt;。因此,您需要更新脚本中的 this 引用。

    $('.sampleBtn').click(function(){
      var row = $(this).closest('td');
      // Changed *this* to *row* below to point at the <td>
      var col = row.parent().children().index(row);
      var id = row.find('.mainId').val();
      var level = row.find('.level').val();
    
      alert("Main ID "+id+" Job ID "+col+" Level "+level);
    });
    

    【讨论】:

    • 哦,那是我忘了..谢谢:)
    【解决方案2】:

    请注意:我认为获取按钮索引的最佳方法是:

    var col = $('.sampleBtn').index(this);
    

    代替:

    var col = row.parent().children().index(row);
    

    试试看:

    https://jsfiddle.net/romadcxn/1/

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多