每次单击按钮时,如何使用jQuery将表格单元格增加1?

时间:2015-04-06 21:02:15

标签: jquery html-table cell increment

这是我的HTML:

<table class="myTable" summary="Table with ages">       
    <tr>
        <th>Name</th>
        <th>Age</th>            
    </tr>   

    <tr>
        <td>Joe</td>
        <td id="joesAge">35</td>
    </tr>

    <tr>
        <td>Becky</td>
        <td id="beckysAge">40</td>
    </tr>

    <tr>
        <td>Joey</td>
        <td id="joeysAge">50</td>
    </tr>                   
</table>

<button onclick="add">Add</button>

每次单击添加按钮时,我都需要将单元格joesAge,beckysAge和joeysAge加1。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

这是一个解决方案:

<script type="text/javascript">
function add(){

    // solution
    // get the row you want
    // get the value, parseInt it and increment by 1
    // replace the content of the row by incremented value

    var joesAgeTd = document.getElementById("joesAge");
    var newJoesAge = parseInt(joesAgeTd.innerHTML) + 1;
    joesAgeTd.innerHTML = newJoesAge;

    var beckysAgeTd = document.getElementById("beckysAge");
    var newbeckysAge = parseInt(beckysAgeTd.innerHTML) + 1;
    beckysAgeTd.innerHTML = newbeckysAge;

    var joeysAgeTd = document.getElementById("joeysAge");
    var newjoeysAge = parseInt(joeysAgeTd.innerHTML) + 1;
    joeysAgeTd.innerHTML = newjoeysAge;
}
</script>
<table class="myTable" summary="Table with ages">
    <tr>
        <th >Name</th>
        <th>Age</th>
    </tr>

    <tr>
        <td>Joe</td>
        <td id="joesAge">35</td>
    </tr>

    <tr>
        <td>Becky</td>
        <td id="beckysAge">40</td>
    </tr>

    <tr>
        <td>Joey</td>
        <td id="joeysAge">50</td>
    </tr>
</table>
<button onclick="add()">Add</button>

答案 1 :(得分:1)

这是显示我的示例解决方案的jsFiddle

$(function () {

    $(document).on('click', 'button', function () {

      var userId = ['#joesAge', '#beckysAge', '#joeysAge'];

      $.each(userId, function (index, value) {

         var age = parseInt($(value).text(), 10);

         if (age) {
             $(value).text(age + 1);
         }

      });
   });
});

我使用.on('click')事件来绑定按钮点击,我还硬编码了td元素ID,它可以(应该)编写以处理任何< / strong>包含单词&#34;年龄&#34;的表格中的元素ID例如。

<强>更新

$(function () {

// bind button click:
$(document).on('click', 'button', function () {

    // array for IDs:
    var items = [];

    // find all TD ID's which contains "Age":
    $(".myTable tr td[id*='Age']").each(function() {

        var id = $(this).attr('id');            

        if(id) {   
            // add *Age IDs ready to be incremented:  
            items.push('#' + id);
        }

     });

    // Loop through all ID's and increment by 1:
    $.each(items, function (index, value) {

        var age = parseInt($(value).text(), 10);

        if (age) {
            $(value).text(age + 1);
        }
    });
});
});

我更新了我的JsFiddle,其处理任何td元素,其属性ID包含单词&#34;年龄&#34;