gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:32:24 25 4
gpt4 key购买 nike

https://plnkr.co/V14X7icWCrmUw6IrCRVV

这是代码的plunker。我从未链接到 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];
}

最佳答案

只需使用一个函数:

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

关于javascript - 如何简化此代码以减少所需的行数? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com