简体   繁体   English

如何在Javascript中将点击事件添加到按钮?

[英]How to add on-click event to button in javascript?

<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>

In the above code what I am trying to do is create number of buttons equal to number inputted in text field and then add an on-click event to those buttons so that when they are clicked the value of each button is rotated. 在上面的代码中,我要尝试创建的按钮数量等于在文本字段中输入的数量,然后向这些按钮添加一个on-click事件,以便在单击它们时旋转每个按钮的值。 The method I have used for getting an onclick event is not working properly. 我用于获取onclick事件的方法无法正常工作。 Help me!! 帮我!!

Several issues here. 这里有几个问题。

1) Use meaningful variable names. 1)使用有意义的变量名。 x and p are hardly indicative and will make life difficult when you come back to the code one day and wonder what they do. xp几乎不是指示性的,当您有一天回到代码中并想知道它们的作用时,将会使工作变得困难。 (They also hinder people trying to help you on Stack Overflow, who have to first interpret them.) (它们还阻碍了必须首先解释它们的人,他们试图在Stack Overflow上为您提供帮助。)

2) You don't need to do document.getElementById("x"+i).onclick - you already have a reference to the button in x so you can just do x.onclick . 2)您不需要执行document.getElementById("x"+i).onclick您已经对x的按钮有一个引用,因此您可以执行x.onclick

3) As a rule, don't use DOM-0 events (eg .onclick ). 3)通常,不要使用DOM-0事件(例如.onclick )。 These allow you only one of each type and are less manageable. 这些仅允许您使用每种类型中的一种,并且较不易于管理。 Instead, use .addEventListener() . 而是使用.addEventListener()

4) As per @Alex Kudryashev's comment, you are making the common beginner mistake of trying to reference an iterative variable inside an asynchronous closure. 4)根据@Alex Kudryashev的评论,您正在犯一个常见的初学者错误,即尝试在异步闭包中引用迭代变量。 In other words, by the time rotate() runs, p will always evaluate to the last value of i , because it happens after the loop has finished. 换句话说,到rotate()运行时, p始终将计算为i的最后一个值,因为它发生在循环完成之后。 Instead, you need to pass a run-time copy of i in at the point of binding the event handler. 相反,您需要在绑定事件处理程序时传递i的运行时副本。 This can be done with the help of an immediately-executed function which returns the event handler. 这可以借助返回事件处理程序的立即执行的函数来完成。 (This can be a little daunting if you're new to JS and is thus outside the scope of this answer. Look it up, though.) (如果您不熟悉JS,这可能会有些令人生畏,因此超出了此答案的范围。不过请查找。)

5) Rather than binding separately to each and every button, look into event delegation. 5)而不是分别绑定到每个按钮,而是研究事件委托。 This makes your code more efficient and can help performance when you're dealing with an appreciably high number of elements and events. 当您处理大量元素和事件时,这将使代码更高效,并有助于提高性能。

All in all, try this: 总而言之,请尝试以下操作:

x.addEventListener('click', (function(i_local_copy) { return function() {
    rotate(i_local_copy);
}; })(i));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM