如何在实际达到限制时执行代码

时间:2011-11-01 19:39:47

标签: javascript

我有这组代码,它将display:none css类添加到我页面上的某个元素。虽然这有效,但我需要代码在显示的15 th 输入值时将样式应用于元素。现在,它在创建输入并再次单击按钮后应用样式。我需要它在创建15 th 输入字段时消失。

有什么想法吗?

 <script> 
>            var counter = 1; 
>            var limit = 15; 
>            function addInput(divName){
> >             if (counter == 15)  {       
>                 var el = document.getElementById('destroy');      
>                 el.style.display = "none";
> >               }
> >             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++;
> >             }
> > 
> > }  </script>

2 个答案:

答案 0 :(得分:1)

我猜你正在努力做到这一点:

var counter = 1; 
var limit = 15; 
function addInput(divName){
  if (counter < limit)  {       
    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++;
    if(counter === limit){
      var el = document.getElementById('destroy');      
      el.style.display = "none";
    }
  }
}

答案 1 :(得分:0)

简单的重新排列应该可以解决问题:

function addInput(divName){
    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++;
    if (counter == 15)  {       
        var el = document.getElementById('destroy');      
        el.style.display = "none";
    }
}