<html>
<body>
<input type="text" id="number"/>
<input type="button" value="create button" onclick="createbtn()"/>
<br>
<script>
function createbtn()
{
var n=document.getElementById("number").value;
for(i=1;i<=n;i++)
{
var x = document.createElement("INPUT");
x.setAttribute("type", "button");
x.setAttribute("value", i);
x.setAttribute("id","x"+i);
document.body.appendChild(x);
document.getElementById("x"+i).onclick=function(){rotate(i)};
}
}
function rotate(p)
{
var n=document.getElementById("number").value;
var j=n;
var k=0;
for(i=n;i>p;i--)
{
document.getElementById("x"+i).value=i-p;
}
for(i=1;i<=p;i++)
{
document.getElementById("x"+i).value=(j-(p-1))+k;
k++;
}
}
</script>
</body>
</html>
在上面的代碼中,我正在嘗試創建的按鈕的數量等於文本字段中輸入的數字,然後向這些按鈕添加一個點擊事件,以便當它們被點擊時,每個按鈕的值是旋轉。我用於獲取onclick事件的方法無法正常工作。幫我!!如何在javascript中添加點擊事件按鈕?
這是在循環使用閉包的經典錯誤。閱讀關於您的代碼的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures。 –