简体   繁体   English

如何使用 JavaScript 将移动 function 添加到多个项目

[英]How to add move function to multiple items with JavaScript

I'm trying to add a move function to multiple items on a page with Javascript - a simple increase in the Y axis.我正在尝试使用 Javascript 将移动 function 添加到页面上的多个项目 - Y 轴的简单增加。 I'm new to Javascript and have been getting an error message for the following code, is it something I am missing?我是 Javascript 的新手,并且收到以下代码的错误消息,这是我遗漏的东西吗?

for the script:对于脚本:

const eyes = document.querySelectorAll('.character');

function move(){
    this.classList.toggle('move');
}

eyes.forEach(eyes => character.addEventListener('click', move));

I'm am getting the following error message:我收到以下错误消息:

uncaught ReferenceError: character is not defined at NodeList.forEach (<anonymous>)

You need to declare your variables.你需要声明你的变量。 The code you're using for your forEach function declares a locally scoped eyes for use inside your function, not character .您用于forEach function 的代码声明了在 function 内部使用的局部范围的eyes ,而不是character

eyes.forEach(eyes => character.addEventListener('click', move));

in your code above, character is not declared and doesn't exist.在您上面的代码中,字符未声明且不存在。

Try something like this:尝试这样的事情:

 const eyes = document.querySelectorAll('.eyes'); function move(){ this.classList.toggle('move'); } eyes.forEach(eye => eye.addEventListener('click', move));
 .character { width: 50px; height: 50px; border: 1px solid black; }.eyes { display: inline-block; width: 10px; height: 10px; border: 1px solid red; }.move { border: 1px solid green; }
 <div id="world"> <div class="character"><div class="eyes"></div><div class="eyes"></div></div> <div class="character"><div class="eyes"></div><div class="eyes"></div></div> <div class="character"><div class="eyes"></div><div class="eyes"></div></div> </div>

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

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