将动态添加的列限制为表

时间:2014-05-28 03:37:27

标签: 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>

1 个答案:

答案 0 :(得分:1)

获取列数(如果您开始使用colspans,则需要更改以反映该值):

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事件时列计数仅为。这意味着一旦Ajax响应到达,列数可能会更多。如果正在进行Ajax调用,您需要取消请求,或者重新设计以便您不会进行如此多的HTTP调用(无论如何这都是不好的做法,类似于网络上所有性能改进的68%)在减少HTTP调用中发现。)