Javascript jQuery-获取表单元格值
我有一张如下所示的桌子。价格通常来自一个数据库,这只是为了显示我的问题Javascript jQuery-获取表单元格值,javascript,jquery,Javascript,Jquery,我有一张如下所示的桌子。价格通常来自一个数据库,这只是为了显示我的问题 $(文档).ready(函数(){ $(文档).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(); 警报(价格); }
$(文档).ready(函数(){
$(文档).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();
警报(价格);
}));
});代码>
门票:
20,50
像这样更改代码
$(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_标题或.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);
}));
});
这是因为price
和sub_total
不是当前元素的子元素(如所选):
它们是其父容器的兄弟,或者更简单地说是容器的子容器tr
请尝试:
var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();
一个例子
<table id="#myTable">
使用'input[type=“text”].amount'
而不是'。amount input[type=“text”]
注意空格已被删除,您应该使用on()
而不是delegate()
。您可以看到,这个问题已经存在了2年,并且当时已经得到了回答。这些函数也不够通用,无法解决我遇到的问题。
<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);