2016-12-29 54 views
1

我想让我的代码在单击按钮时向我显示数组的内容。如何在点击X后禁用按钮?

一个点击array[0],第二个为array[1]等我得到它,但我不知道如何禁用按钮(或只是停止功能)时,我的阵列已经用完的内容。我尝试了一些简单的for循环,但它不起作用。

var writing = (function() { 
 
    var myArray = ["one ", "two ", "three!"]; 
 
    var counter = -1; 
 
    return function() { 
 
    return myArray[counter += 1]; 
 
    } 
 
})(); 
 

 
function buttonFunction() { 
 
    document.getElementById('parag').innerHTML += writing(); 
 
}
<button onclick='buttonFunction()'>Click</button> 
 
<p id="parag">...</p>

回答

2

试试这个

var counter = -1; 
 

 
var writing = (function() { 
 
     var myArray = ["one ","two ","three!"]; 
 
     return function(){return myArray[counter+=1];} 
 
    })(); 
 

 
    function buttonFunction(self) { 
 
    document.getElementById('parag').innerHTML += writing(); 
 
     if(counter == 2) 
 
     self.disabled = true; 
 
     }
<button onclick='buttonFunction(this)'>Click</button> 
 
    <p id="parag">...</p>

可变counter必须是全球性认识的点击当前count

+0

为什么不'this'?只是好奇。 –

+0

@PraveenKumar不确定。如果有任何请让我知道。对我和OP也很有帮助。 –

+0

我不知道,这就是为什么我问你...我问你为什么用'self'而不是'this' ... –

0

对不起,我最初的错误。 只需检查writing()方法返回的匿名函数counter即可达到myArray.length。在这种情况下,禁用这样的按钮:

return function(){ 
    if(++counter < myArray.length) 
    return myArray[counter]; 
    else 
    return ""; 
} 

return function(){ 
    if(++counter < myArray.length) 
    return myArray[counter]; 
    self.disabled=true; 
    return ""; 
} 
0

的另一种方法,它不需要保持跟踪指数:

<button id="btn">Click</button> 
<p id="parag">...</p> 

<script> 
    var myArray = ["one", "two", "three!"]; 

    var button = document.getElementById('btn'); 

    // If array is empty at the beginning, disable the button immediately 
    if(myArray.length === 0) button.disabled = true; 

    button.addEventListener('click', function(event) { 

     document.getElementById('parag').innerText += myArray.shift(); 
     if(myArray.length === 0) this.disabled = true; 

    }); 

</script> 

myArray.shift()移除第一元件(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift),然后检查Array是否为空,如果是,则禁用该按钮。

Btw。不要直接在元素上使用onClick(Why is using onClick() in HTML a bad practice?