简体   繁体   English

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

[英]How do I simplify this code to reduce the amount of lines necessary? (Javascript)

https://plnkr.co/V14X7icWCrmUw6IrCRVV https://plnkr.co/V14X7icWCrmUw6IrCRVV

That's the plunker for the code. 那是代码的浪费。 I've never linked to plunker so if it doesn't work, let me know. 我从来没有链接到pl子,所以如果它不起作用,请告诉我。

What it is supposed to do is when a user hovers over some of the text, that same text should appear in the yellow box. 应该做的是,当用户将鼠标悬停在某些文本上时,相同的文本应出现在黄色框中。

I thought I should have been able to do it with just a few lines, and substituting the index number with a variable, and looping through them with a while loop. 我以为我应该只用几行就可以完成,并用一个变量替换索引号,并使用while循环遍历它们。 I couldn't quite figure it out and had to just make like 20 different functions. 我不太清楚,只能做20个不同的功能。 I got it to do what I wanted it to do, but I can't help but think there should be a simpler way to do it. 我让它做我想做的事,但我不禁认为应该有一个更简单的方法来做。

Here is the Javascript: (The plunker link has the CSS and HTML) 这是Javascript:(punker链接包含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];
        }

Just use one function: 只需使用一个功能:

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

Use this function and then replace any of the other function calls. 使用此函数,然后替换任何其他函数调用。 Example choice003() is replaced with choice(3) 示例choice003()替换为choice(3)

I like that you doubt your solution, because it is indeed overwhelming! 我喜欢您怀疑您的解决方案,因为它确实势不可挡! It's a very important rule: if you see certain pattern, repetition of some kind, you can always make it shorter. 这是一条非常重要的规则:如果您看到某种模式,某种形式的重复,则总是可以使其更短。

First of all, you need to decide if your items are already created in HTML or do you want to create them using JavaScript. 首先,您需要确定您的项目是否已经以HTML创建,还是要使用JavaScript创建。 In other words: you should have only one source of data. 换句话说:您应该只有一个数据源。 In your example you'd need to maintain two data sources at once — array in JavaScript and list in HTML. 在您的示例中,您需要一次维护两个数据源-JavaScript中的数组和HTML中的列表。

HTML-driven data HTML驱动的数据

It's extremely important to separate HTML and JavaScript as much as possible. 尽可能地分离HTML和JavaScript是非常重要的。 Below you'll find a working example without even a smallest amount of any JS functions or events. 在下面,您将找到一个工作示例,该示例甚至没有任何JS函数或事件的最小数量。

If you design your code that way it's easier to keep track of everything, as it stays simple. 如果您以这种方式设计代码,那么就可以更轻松地跟踪所有内容,因为它保持简单。 JavaScript code below has only around 6 real-lines and it can be simplified even more! 下面的JavaScript代码只有大约6条实线,并且可以进一步简化!

If you need to provide any additional data in the box, that are not visible to the user by default, you can use data attributes . 如果您需要在框中提供默认情况下用户不可见的任何其他数据,则可以使用data属性

I've used jQuery since I'm used to it, but you can easily achieve the same effect with roughly the same amount of lines with pure JavaScript . 自从我开始使用jQuery以来,我就一直使用它,但是使用纯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> 

Extra thought 额外的想法

I noticed that in your JavaScript code you're changing borderColor and color of .answerBox . 我注意到,在您的JavaScript代码中,您正在更改borderColor.answerBox color You should never do that . 你绝对不要那样做

As it's part of visual styles, you should define adequate styles beforehand in your CSS file and then, toggle certain classes as needed. 由于它是视觉样式的一部分,因此您应该事先在CSS文件中定义适当的样式,然后根据需要切换某些类。 For example, below code is much easier to maintain: 例如,以下代码更易于维护:

 /*/ 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 
 /*/ 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; } 
 <p>Very nice paragraph</p> 

Stay pure! 保持纯洁!
~Wiktor 〜威克多

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

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