使用jQuery遍历表单元格 [英] Iterating through table cells using jquery
问题描述
我有一个包含可变列数的表.我编写了一个函数来遍历每一行中的每个单元,以执行以下操作:
I have a table containing a variable number of columns. I wrote a function to iterate through each cell in each row to do the following:
- 检查输入是否存在
- 获取输入值
- 将饼状图附加到条件#1计算为true的任何单元格中
这是我的代码:
function addPieCharts() {
var htmlPre = "<span class='inlinesparkline' values='";
var htmlPost = "'></span>"
var colors = ["red", "blue"];
$("#MarketsTable tr").each(function () {
$('td').each(function () {
var value = $(this).find(":input").val();
var values = 100 - value + ', ' + value;
if (value > 0) {
$(this).append(htmlPre + values + htmlPost);
}
})
})
$('.inlinesparkline').sparkline('html', { type: 'pie', sliceColors: colors });
}
步骤1-3基本如上所述.在运行此过程时,会将饼图添加到显示正确值的正确单元格中.我的问题是,我期望每个存在输入的单元格只有一个饼图.但是,我每个单元格都有n个饼图,其中n等于表中的列数.我怀疑我错误地使用了jQuery的each()方法.有人可以告诉我我做错了什么吗?
Steps 1-3 are basically working as described. When this runs the pie charts are added to the correct cells displaying the correct values. My problem is that I'm expecting just one pie chart per cell where there exists an input. However, I have n pie charts per cell where n is equal to the number of columns in the table. I suspect I'm using jQuery's each() method incorrectly. Can someone tell me what I've done wrong?
推荐答案
选择td
时,将上下文作为tr(this
)传递,以便仅在当前tr
中查找td
.试试这个.
When you select td
pass the context as tr(this
) so that it will look for td
only in the current tr
. Try this.
$("#MarketsTable tr").each(function () {
$('td', this).each(function () {
var value = $(this).find(":input").val();
var values = 100 - value + ', ' + value;
if (value > 0) {
$(this).append(htmlPre + values + htmlPost);
}
})
})
这篇关于使用jQuery遍历表单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!