2014-09-10 145 views
1

我有一个表,如下所示:jQuery的 - 获取表格单元格值

<table> 
<tr> 
     <td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td> 
     <td>Ticket:</td> 
     <td class="price"><?= number_format(20.5), 2, ',', '.'); ?></td> 
     <td class="sub_total"></td> 
    </tr> 
</table> 

价格通常来自一个数据库,这只是用于显示我有问题。 用下面的jQuery:

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

我想要做的是:当用户在该领域tickets一些应该更新领域sub_total。与jQuery我有这不工作。当我警觉(价格)我得到未定义。所以我想知道如何使sub_total字段具有自动更新的值。知道我在这一行下面有更多这样的行也是很有趣的。所以脚本一次只能更新一个特定行的字段。

我已经试过但没有成功: How to get a table cell value using jquery; How to get a table cell value using jQuery?; How to get table cell values any where in the table using jquery

在此先感谢。

+1

使用''输入[类型= “文本”]代替amount'' '.amount input [type =“text”]''注意空间被删除 – Satpal 2014-09-10 11:20:34

+0

你应该使用'on()'而不是'delegate()'。 – 2014-09-10 11:20:56

回答

1

您需要在试图找到.sub_title或元素。价格之前做回穿越到父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); 
    })); 
}); 
1

更改你像这样的代码

$(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元素

0

这是因为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(); 
-1

例如用于

<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); 
+0

正如你所看到的问题已经2岁了,并已经回答了。这些功能还不足以解决我所遇到的问题。 – SuperDJ 2016-08-16 09:13:36