减少代码JavaScript的数量

时间:2016-03-13 19:12:30

标签: javascript javascript-events

在此示例中,如何减少JavaScript代码的数量?我想要DRY代码。

我希望知道我需要做什么才能不使用EventListeners重复自己。

请在此处找到代码。首先是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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

Loopsfunctions是将相同操作应用于多个值的常用方法。

将元素放在数组中,迭代器放在它上面:

var elements = [firstLi, /*...*/];

elements.forEach(function(element) {
   element.addEventListener(/*...*/);
   // ...
});

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

li:hover {
  color: green;
}

答案 1 :(得分:2)

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

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>

答案 2 :(得分:0)

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