2015-09-09 386 views
1

如何使用下面的代码,只能单击按钮一次,然后才会执行任何操作。提前致谢!只能按一次JavaScript按钮

<button onClick="yumpizza();"style="position:absolute; TOP:120px; LEFT:350px">Roll for strength</button> 

<script> 
    var strength = Math.floor(Math.random() * 20 + 1); 
    function yumpizza() { 
    document.getElementById("pizza").innerHTML = ("Strength:" + strength) 
} 
</script> 

回答

1

只需设置元素的onclick事件的首次触发后空:

<button id="pizzaButton" onClick="yumpizza();" style="position:absolute; TOP:120px; LEFT:350px">Roll for strength</button> 

<script> 
    var strength = Math.floor(Math.random() * 20 + 1); 
    function yumpizza() { 
    document.getElementById("pizza").innerHTML = ("Strength:" + strength); 
    document.getElementById("pizzaButton").onclick = null; 
    } 
</script> 

就说明事件处理的,是被使用addEventListener以编程方式设置事件处理程序的最佳实践,而不是onclick HTML属性。

+0

谢谢!这很有效。 – ProVideoCreator

+1

@ProVideoCreator你必须接受答案新手;) – webdeb

+1

@ProVideoCreator如果它解决了你的问题,不要忘了接受它作为答案。此外,您可能想尝试使用'disabled'属性,因为它会改变按钮的样式。 – PitaJ

0

再添加一个线yumpizza()函数:

document.getElementById("pizzaButton").disabled = true; 
0

你也可以使用jQuery:

var strength = Math.floor(Math.random() * 20 + 1); 
    function yumpizza() { 
    document.getElementById("pizza").innerHTML = ("Strength:" + strength) 
} 
$('button').on('click', function() { 
    $(this).disable(); 
}); 

这里是小提琴例如:http://jsfiddle.net/eugensunic/tnaZV/530/

+0

我不太喜欢jQuery,但感谢您的帮助! – ProVideoCreator