2015-04-06 52 views
-1

这里是我的html:每次单击按钮时,如何使用jQuery将表格单元格增加1?

<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所需要的细胞joesAge,beckysAge和joeysAge每个增量每添加按钮被点击的时间。有人可以帮我吗?

+0

你好米歇尔标志ID,请确保您已经发布你”已经尝试过。 – technophobia

+0

我编辑了您的文章,以便您的HTML格式更好。如果你能够发布你已经尝试过的jQuery,我相信有人能够帮助你解决你的问题。 –

回答

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

这里是一个jsFiddle显示我的示例解决方案。

我已经使用了.on('click')事件到按钮上单击绑定,我也硬编码的td元素的ID的可能(应该)被写入处理任何元素ID中包含单词“表年龄“。

UPDATE

$(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元素包含单词“时代”

相关问题