簡體   English   中英

jQuery-獲取表單元格值

[英]jQuery - Get table cell value

我有一張看起來像下面的桌子。 價格通常來自數據庫,僅用於顯示我的問題。

 $(document).ready(function() { $(document).delegate('.amount input[type="text"]','keyup',(function() { var $this = $(this); var sub_total = $this.find('.sub_total'); var price = $this.find('.price').text(); var amount = $this.val(); alert(price); })); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td> <td>Ticket:</td> <td class="price">20,50</td> <td class="sub_total"></td> </tr> </table> 

我想做的是:當用戶在字段tickets輸入數字時,應該更新sub_total字段。 使用jQuery,我無法正常工作。 當我alert(price)undefined 所以我想知道如何使sub_total字段具有自動更新的值。 知道我在此行下還有更多行可能也很有趣。 因此,腳本一次只能更新一個特定行中的字段。

我已經嘗試過但沒有成功的事情如何使用jQuery獲取表單元格值 如何使用jQuery獲取表格單元格值? ; 如何使用jQuery在表中的任何位置獲取表單元格值

提前致謝。

像這樣更改您的代碼

$(document).ready(function() {
    $(document).on('input[type="text"].amount', 'keyup', (function() {
        var $this = $(this);
        var sub_total = $this.closest("tr").find('.sub_total');
        var price = $this.closest("tr").find('.price').text();
        var amount = $this.val();
        alert(price);
    }));
});

find()將搜索子級。 因此,在使用find()之前,您應該先進入父級tr

您可以使用closest("tr")來獲取父級tr元素

在嘗試查找.sub_title或.price元素之前,需要遍歷到父tr元素。

$(document).ready(function() {
    $(document).delegate('.amount input[type="text"]','keyup',(function() {
        var $this = $(this);
        var $tr = $this.closest("tr");
        var sub_total = $tr.find('.sub_total');
        var price = $tr.find('.price').text();
        var amount = $this.val();
        alert(price);
    }));
});

這是因為pricesub_total不是當前元素的子元素(如find所選擇):

var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();

它們是其容器tr父級或更簡單的子級的同級。

請嘗試:

var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();

一個例子

<table id="#myTable">

我這樣寫:

function setCell( idTab, row, col, text) {
  var idCel = idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
  $(idCel).html(text);
}

function getCell( idTab, row, col ) {
  var idCel =idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
  return $(idCel).html();
}

setCell( "#myTab", 3, 4, "new value" );
alert( getCell("#myTab", 3, 4);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM