javascript - 限制向表动态添加的列

标签 javascript jquery ajax

请看一下这个 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
});

参见this working Fiddle

注意:由于您要在 Ajax Success 结果上添加列,因此列计数仅在 click 事件发生时才为 true 。这意味着一旦 Ajax 响应到达,列数可能会更多。如果正在进行 Ajax 调用,您需要取消请求,或者重新设计,这样您就不会进行如此多的 HTTP 调用(无论如何,这都是不好的做法,网络上 68% 的性能改进都在减少 HTTP 调用。)

关于javascript - 限制向表动态添加的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902420/

相关文章:

javascript - 使用对象引用调用 setinterval

javascript - 在 ie11 上使用 jquery 滚动会出现抖动元素问题

javascript - 使用 JavaScript 过滤 Firebase 查询

javascript - 我想结合 jQuery、AJAX 和 Flask,但无法从服务器获取响应以在模板上写入

ajax - fastcgi_finish_request 在打开 session 存在时创建挂起连接

javascript - HMVC Codeigniter 中没有 'Access-Control-Allow-Origin' 错误

php - 用户自定义样式是否可以与 document.ready + localStorage 一起使用?

javascript - 引用错误 : is not defined

jquery - 如何使 jQuery Coda-Slider 居中?

jQuery 处理表单