限制添加行功能不起作用,请帮忙

时间:2010-11-02 04:53:26

标签: javascript function limit add

这是一个带有函数的简单javascript添加行,然后我不知道如何限制附加行,例如最大5行,任何想法和指针或示例我将不胜感激

<script type="text/javascript">
function addRow() {
var newRow = document.all("tblGrid").insertRow();
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t1'><input type='button' value='Delete' onclick='removeRow(this);'/>"; 
//if(oCell>=5)return; 
}
</script>

提前致谢

2 个答案:

答案 0 :(得分:1)

添加前计算行数。行只是表元素中的一个数组 - 您可以通过length

获取其长度
<script type="text/javascript">
function addRow() {
    if (document.all("tblGrid").rows.length == 5) {
        return; // already max 5 rows
    }
    var newRow = document.all("tblGrid").insertRow();
    oCell = newRow.insertCell();
    oCell.innerHTML = "<input type='text' name='t1'><input type='button' value='Delete' onclick='removeRow(this);'/>"; 
}
</script>

答案 1 :(得分:0)

var counter =1;
var limit = 5;
function addInput(yourDivName){
if (counter==5) {
     *the code you want to execute if the limit is reached* }
else {
     var newdiv = document.createElement('div');
     newdiv.innerHTML = "<span id=''>Serial Number " + (counter + 1) + " : <input type='text' name='myInputs[]'/></span>";
     document.getElementById(divName).appendChild(newdiv);
     counter++;
     }
}