Smaller amounts of JavaScript


在这个

例子中,如何减少我的JavaScript代码量?我想要干代码。

我想知道我需要做什么才能避免重复事件侦听器。

请在此处找到代码。首先是JavaScript,然后是CSS,然后是HTML。

var firstLi = document.querySelector("#one");
var secondLi = document.querySelector("#two");
var thirdLi = document.querySelector("#three");
firstLi.addEventListener("click", done);
secondLi.addEventListener("click", done);
thirdLi.addEventListener("click", done);
firstLi.addEventListener("mouseover", hover);
secondLi.addEventListener("mouseover", hover);
thirdLi.addEventListener("mouseover", hover);
firstLi.addEventListener("mouseout", hoverOut);
secondLi.addEventListener("mouseout", hoverOut);
thirdLi.addEventListener("mouseout", hoverOut);
function done() {
  this.classList.toggle("greyout");
}
function hover() {
  this.classList.add("hover");
}
function hoverOut() {
  this.classList.remove("hover");
}
.hover {
  color: green;
}
.greyout {
  color: grey;
  text-decoration: line-through;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>to do's</title>
    <link rel="stylesheet" href="css/todo.css" media="screen" title="no title" charset="utf-8">
  </head>
  <body>
    <ul>
      <li id="one">One</li>
      <li id="two">Two</li>
      <li id="three">Three</li>
    </ul>
  <script src="todo.js" charset="utf-8"></script>
  </body>
</html>

循环和函数是将相同操作应用于多个值的常用方法。

将元素放在数组中并在其上迭代器:

var elements = [firstLi, /*...*/];
elements.forEach(function(element) {
   element.addEventListener(/*...*/);
   // ...
});

但正如评论中提到的,悬停效果可以在没有任何 JavaScript 的情况下实现,使用 :hover CSS 选择器:

li:hover {
  color: green;
}

可以使用事件委派并在列表中添加一个事件侦听器:

var list = document.querySelector("ul");
list.addEventListener("click", done);
function done(e) {
  if (e.target.tagName === 'LI') {
    e.target.classList.toggle("greyout");
  }
}
   
li:hover {
  color: green;
}
.greyout {
  color: grey;
  text-decoration: line-through;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>to do's</title>
    <link rel="stylesheet" href="css/todo.css" media="screen" title="no title" charset="utf-8">
  </head>
  <body>
    <ul>
      <li id="one">One</li>
      <li id="two">Two</li>
      <li id="three">Three</li>
    </ul>
  <script src="todo.js" charset="utf-8"></script>
  </body>
</html>

function multipleHandler(element, events, handler){
        for(var iloop=0; iloop< events.length; iloop++){
           element.addEventListener(events[iloop], (function handlerFn(){
              return handler[iloop];
           })() );
        }
}

最新更新