请看一下这个 fiddle example 。我正在使用 AJAX 单击添加新列。有没有办法计算表的列数并将新列的数量限制为 6?有人可以给我建议吗?
jQuery:
$(function () {
var ajaxfunction = function(){
$('.area').on("click","button", function(){
var source = $(this).data('feed');
$.ajax({
url: source,
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title,
year = item.year,
job = item.Job,
education = item.Education,
background = item.Background,
ingredient = item.Ingredient;
$('#header').after('<th>'+title+'</th>')
$('#ingredient').after('<td>'+ingredient+'</td>')
$('#year').after('<td>'+year+'</td>')
$('#background').after('<td>'+background+'</td>')
$('#education').after('<td>'+education+'</td>')
$('#job').after('<td>'+job+'</td>')
});
$('#toptable').stickyTableHeaders(); //Fixed Header Plugin
},
});
});
}
ajaxfunction();
});
HTML
<div class="area">
<button>Class B</button>
<button>Class C</button>
<button>Class D</button>
</div>
<table id="toptable">
<thead>
<tr>
<th id="header" style="visibility:hidden">-</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ingredient">Ingredient</td>
</tr>
<tr>
<td id="year">Year</td>
</tr>
<tr>
<td id="background">Background</td>
</tr>
<tr>
<td id="education">Education</td>
</tr>
<tr>
<td id="job">Job</td>
</tr>
</tbody>
</table>
最佳答案
获取列数(如果您开始使用 colspans,则需要更改以反射(reflect)这一点):
var colcount = $("#toptable").find("tr:first th").length;
或
var colcount = $("tr:first th", "#toptable").length;
或
var colcount = $("#toptable tr:first th").length;
限制列数(已测试和工作):
$('.area').on("click","button", function(){
var colspan = $("#toptable tr:first th").length;
alert("Current number of Columns = " + colspan);
if(colspan > 6)
{
alert("Too Many Columns");
return false;
}
var source = $(this).data('feed');
//the rest of your code
});
注意:由于您要在 Ajax Success 结果上添加列,因此列计数仅在 click
事件发生时才为 true 。这意味着一旦 Ajax 响应到达,列数可能会更多。如果正在进行 Ajax 调用,您需要取消请求,或者重新设计,这样您就不会进行如此多的 HTTP 调用(无论如何,这都是不好的做法,网络上 68% 的性能改进都在减少 HTTP 调用。)
关于javascript - 限制向表动态添加的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902420/