事件处理程序在循环中分配的方式与我的预期相悖。

huangapple go评论78阅读模式
英文:

Event handling assigned in a loop works against my expectations

问题

const radio = document.getElementsByName('subject');

for (let i = 0; i < radio.length; i++) {
    radio[i].onclick = () => {
        alert(`You chose ${radio[i].value}.`);
    };
}
<form name="testForm">
   <fieldset>
      <legend>Subject List</legend>
      <p>Choose your favorite subject.</p>
      <label><input type="radio" name="subject" value="speaking">Speaking</label>
      <label><input type="radio" name="subject" value="grammar">Grammar</label>
      <label><input type="radio" name="subject" value="writing">Writing</label>       
   </fieldset>
</form>
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const radio = document.getElementsByName(&#39;subject&#39;);

for (let i = 0; i &lt; radio.length; i++) {
    radio[i].onclick = () =&gt; {
        alert(`You chose ${radio[i].value}.`);
    };
}

<!-- language: lang-html -->

&lt;form name=&quot;testForm&quot;&gt;
   &lt;fieldset&gt;
      &lt;legend&gt;Subject List&lt;/legend&gt;
      &lt;p&gt;Choose your favorite subject.&lt;/p&gt;
      &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;subject&quot; value=&quot;speaking&quot;&gt;Speaking&lt;/label&gt;
      &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;subject&quot; value=&quot;grammar&quot;&gt;Grammar&lt;/label&gt;
      &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;subject&quot; value=&quot;writing&quot;&gt;Writing&lt;/label&gt;       
   &lt;/fieldset&gt;
&lt;/form&gt;

<!-- end snippet -->

for-loop runs only once when the document is loaded, but I don't know why the alert pops up every time I click the input.

Shouldn't "radio.onclick" be outside to act as a trigger?

答案1

得分: 0

for-loop runs only once when the document is loaded, but I don't know why the alert pops up every time I click the input.
当文档加载时,for循环只运行一次,但我不知道为什么每次点击输入时警报都会弹出。

The loop goes to each radio button in turn. Inside the loop you say "When this radio button is clicked, run this function".
循环逐个选择每个单选按钮。在循环内部,您说:“当单选按钮被点击时,运行此函数”。

You click a radio button, the function runs. You click it again, the function runs again.
您点击单选按钮,函数运行。再次点击它,函数会再次运行。

You never tell it to stop doing things when you click a radio button so there's no reason for it not to run the function every time you click an input.
您从未告诉它在单击单选按钮时停止执行操作,因此没有理由不在每次单击输入时运行该函数。

Shouldn't "radio.onclick" be outside to act as a trigger?
“radio.onclick”不应该放在外面作为触发器吗?

Then you would be trying to say "When this Node List is clicked, call this function."
然后,您将尝试说:“当单击此节点列表时,请调用此函数。”

There are two problems with that.
这种方法存在两个问题。

  1. Node Lists are somewhat abstract. They aren't things you can click on. So assigning an onclick property does nothing.
    节点列表有点抽象。它们不是您可以单击的东西。因此,分配onclick属性不起作用。

  2. Since you are proposing putting the loop inside the function you assign to onclick then, if point 1 was not true, a single click on any radio button (i.e. anywhere on the Node List) would trigger the loop and make three alerts (one for each radio button).
    由于您建议将循环放在分配给onclick的函数内部,因此,如果点1不成立,那么任何单选按钮上的单击(即在节点列表的任何地方)都将触发循环并产生三个警报(每个单选按钮一个)。


Asides:

  • onclick assignments have some drawbacks (you can't assign multiple event listeners, assigning one to the wrong kind of object generally fails silently instead of producing an error). It is recommended to use addEventListener instead.
  • onclick分配存在一些缺点(无法分配多个事件侦听器,将其分配给错误类型的对象通常会静默失败而不会生成错误)。建议改用 addEventListener
英文:

> for-loop runs only once when the document is loaded, but I don't know why the alert pops up every time I click the input.

The loop goes to each radio button in turn. Inside the loop you say "When this radio button is clicked, run this function".

You click a radio button, the function runs. You click it again, the function runs again.

You never tell it to stop doing things when you click a radio button so there's no reason for it not to run the function every time you click an input.

> Shouldn't "radio.onclick" be outside to act as a trigger?

Then you would be trying to say "When this Node List is clicked, call this function."

There are two problems with that.

  1. Node Lists are somewhat abstract. They aren't things you can click on. So assigning an onclick property does nothing.
  2. Since you are proposing putting the loop inside the function you assign to onclick then, if point 1 was not true, a single click on any radio button (i.e. anywhere on the Node List) would trigger the loop and make three alerts (one for each radio button)

Asides:

  • onclick assignments have some drawbacks (you can't assign multiple event listeners, assigning one to the wrong kind of object generally fails silently instead of producing an error). It is recommended to use addEventListener instead.
  • The approach for binding a single event listener which handles multiple similar UI controls is called event delegation.

huangapple
  • 本文由 发表于 2023年7月20日 17:03:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定