如何简化此代码以减少必要的行数? (JavaScript)的

时间:2017-01-15 23:03:21

标签: javascript html css

https://plnkr.co/V14X7icWCrmUw6IrCRVV

这是代码的掠夺者。我从来没有联系到plunker,所以如果它不起作用,请告诉我。

它应该做的是当用户将鼠标悬停在某些文本上时,相同的文本应出现在黄色框中。

我以为我应该能够用几行代替它,并用变量代替索引号,并用while循环遍历它们。我无法弄明白,只能制作20种不同的功能。我得到它做我想做的事情,但我不禁想到应该有一个更简单的方法去做。

这是Javascript :( plunker链接有CSS和HTML)

   var gamesArray = ['Metal Gear Solid 1', 'The Last of Us', 'Uncharted', 'Snake Eater', 'Need for Speed', 'Forza', 'Halo', 'Conker\'s Bad Fur Day', 'WWF No Mercy', 'WWF Wrestlemania 2000', 'Spelunky', 'The Last of Us Part 2', 'The Walking Dead Season 1', 'The Phantom Pain', 'Ys Memories of Celceta', 'Ys Seven', 'Dragon Ball Z Tenkaichi Tag Team', 'Naruto: Ultimate Ninja Heroes', 'Mortal Kombat'];

var itemList = document.getElementsByClassName('myClass');
var box2 = document.getElementsByClassName('answerBox');
    box2[0].style.borderColor = 'black';
    box2[0].style.color = 'red';

    //var num = 0;  
    //var i = itemList[num];
    //var j = gamesArray[num];



function choice000(){
box2[0].textContent = gamesArray[0];

        }

function choice001(){
box2[0].textContent = gamesArray[1];
        }

function choice002(){
box2[0].textContent = gamesArray[2];
        }

function choice003(){
box2[0].textContent = gamesArray[3];
        }

function choice004(){
box2[0].textContent = gamesArray[4];
        }

function choice005(){
box2[0].textContent = gamesArray[5];
        }

function choice006(){
box2[0].textContent = gamesArray[6];
        }

function choice007(){
box2[0].textContent = gamesArray[7];
        }

function choice008(){
box2[0].textContent = gamesArray[8];
        }

function choice009(){
box2[0].textContent = gamesArray[9];
        }

function choice010(){
box2[0].textContent = gamesArray[10];
        }

function choice011(){
box2[0].textContent = gamesArray[11];
        }

function choice012(){
box2[0].textContent = gamesArray[12];
        }

function choice013(){
box2[0].textContent = gamesArray[13];
        }

function choice014(){
box2[0].textContent = gamesArray[14];
        }

function choice015(){
box2[0].textContent = gamesArray[15];
        }

function choice016(){
box2[0].textContent = gamesArray[16];
        }

function choice017(){
box2[0].textContent = gamesArray[17];
        }

function choice018(){
box2[0].textContent = gamesArray[18];
        }

function choice019(){
box2[0].textContent = gamesArray[19];
        }

3 个答案:

答案 0 :(得分:0)

只需使用一个功能:

function choice(game){
   box2[0].textContent = gamesArray[game];
}

答案 1 :(得分:0)

function choice(number) {
    box2[0].textContent = gamesArray[number];
}

使用此功能,然后替换任何其他功能调用。示例choice003()替换为choice(3)

答案 2 :(得分:0)

我喜欢你怀疑你的解决方案,因为它确实是压倒性的!这是一个非常重要的规则:如果你看到某种模式,某种重复,你总是可以缩短它。

首先,您需要确定您的项目是否已在HTML中创建,或者您是否要使用JavaScript创建它们。换句话说:您应该只有一个数据源。在您的示例中,您需要同时维护两个数据源 - JavaScript中的数组和HTML中的列表。

HTML驱动的数据

尽可能地分离HTML和JavaScript非常重要。在下面,您将找到一个工作示例,即使没有最少量的任何JS函数或事件。

如果您以这种方式设计代码,则可以更轻松地跟踪所有内容,因为它保持简单。下面的JavaScript代码只有大约6个实线,可以进一步简化!

如果您需要在框中提供默认情况下用户无法看到的任何其他数据,您可以使用data attributes

我已经习惯使用了jQuery,但您可以使用pure JavaScript与大致相同数量的行轻松实现相同的效果。



/*
  We define every event and action only in JavaScript.
  We're keeping HTML *pure* and *simple*.
*/

$(function(){
  var $games = $('.gameChoiceList li');
  
  $games.on('mouseover', function() {  // After moving mouse on any [.gameChoiceList li] element
    var $game = $(this);
    var $result = $('.answerBox');
    
    $result.text($game.text());        // Display current [.gameChoiceList li] text in [.answerBox]
  });
});

/* Styles go here */
body {
  background-color: skyblue;
  font-family: Arial, sans-serif;  /*
     We provide feedback if user doesn't have Arial font installed:
     sans-serif is a group of serif fonts, so possible replacement wont be far from Arial */
}

.answerContainer{ /*
     We don't need width: auto; and height: auto; as those are the default values */
  border-style: solid;
  margin-top: 30px;
}

.testAnswer{
  border-style: solid;
  padding: 10px;
}

.answerBox{
  border-style: solid;
  text-align: center;
  padding: 20px;
  height: 200px;
  width: 50%;
  background-color: yellow;
}

/*/ Extra: /*/
.gameChoiceList {
  float: left;
  padding: 0;
  width: 40%;
}
.gameChoiceList li {
  list-style-type: none;
  margin: 2px;
}
.gameChoiceList li a {
  display: block;
  border: solid 1px;
  background: #fff;
  text-align: center;
  padding: 5px;
}
.answerBox {
  float: right;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul class="gameChoiceList">
  <!--
    We don't need the same class for every <li>, as it is easily accesible by:
          .gameChoiceList li    OR    .gameChoiceList > li
    
    We don't need the same class for every <a>, as it is easily accesible by:
          .gameChoiceList li a    OR    .gameChoiceList a
  -->
  <li><a href="#">Metal Gear Solid 1</a></li>
  <li><a href="#">The Last of Us</a></li>
  <li><a href="#">Uncharted</a></li>
  <li><a href="#">Snake Eater</a></li>
  <li><a href="#">Need for Speed</a></li>
  <li><a href="#">Forza</a></li>
  <li><a href="#">Halo</a></li>
  <li><a href="#">Conker's Bad Fur Day</a></li>
  <li><a href="#">WWF No Mercy</a></li>
  <li><a href="#">WWF Wrestlemania 2000</a></li>
  <li><a href="#">Spelunky</a></li>
  <li><a href="#">The Last of Us Part 2</a></li>
  <li><a href="#">The Walking Dead Season 1</a></li>
  <li><a href="#">Metal Gear Solid V: The Phantom Pain</a></li>
  <li><a href="#">Ys Memories of Celceta</a></li>
  <li><a href="#">Ys Seven</a></li>
  <li><a href="#">Dragon Ball Z Tenkaichi Tag Team</a></li>
  <li><a href="#">Naruto Ultimate Ninja Heroes</a></li>
  <li><a href="#">Mortal Kombat</a></li>
</ul>

<p class="answerBox">Mouseover on any of the games on the side to display its name here.</p>
&#13;
&#13;
&#13;

额外的想法

我注意到,在您的JavaScript代码中,您正在更改borderColor的{​​{1}}和color你永远不应该那样做

作为视觉样式的一部分,您应该事先在CSS文件中定义足够的样式,然后根据需要切换某些类。例如,下面的代码更容易维护:

&#13;
&#13;
.answerBox
&#13;
/*/
  Of course all the code below can be simplified to just 1 line:
      document.querySelector('p').className = 'important';
      
  I wanted to show something universal that helps separate the logic even more:
  You can pass any element, class and content to the make() function.
/*/

var make = function(element, className, content) {
  element.className = className;
  element.textContent = content;
};

var paragraph = document.querySelector('p');

setTimeout(function() {
  make(paragraph, 'important', 'Important paragraph');
}, 1000);  // Make important after 1 second

setTimeout(function() {
  make(paragraph, 'irrelevant', 'Irrelevant paragraph. do dont read it!');
}, 2000);  // Make important after 2 seconds
&#13;
/*/ Since we defined every class beforehand,
    it's easier to adjust styles for certain actions in the future /*/

p {
  color: green;
}

p.important {
  color: red;
  border: solid 1px red;
  padding: 10px;
}

p.irrelevant {
  color: gray;
  font-size: .8em;
}
&#13;
&#13;
&#13;

保持纯洁!
〜Wiktor的