gpt4 book ai didi

javascript - 如何摆脱数千行

转载 作者:行者123 更新时间:2023-12-02 02:29:28 26 4
gpt4 key购买 nike

为了显示学生正在学习哪门类(class),我写了这些简单的行,单击学生并查看类(class),但似乎有数千行代码,因为我应该列出这么多学生和类(class)。有没有办法编写一个函数来获取对象的值,而不是为每次点击编写一个单独的函数?

//and goes on thousands of times like this...
var txt = document.getElementById("txt");
var students = {
student1: "english",
student2: "maths",
student3: "history",
student4: "geography",
student5: "science",
student6: "maths",
student7: "maths",
student8: "history",
student9: "french",
student10: "geography",
};
//and there are thousands of students...

function f1(){txt.innerHTML = students.student1;};
function f2(){txt.innerHTML = students.student2;};
function f3(){txt.innerHTML = students.student3;};
function f4(){txt.innerHTML = students.student4;};
function f5(){txt.innerHTML = students.student5;};
function f6(){txt.innerHTML = students.student6;};
function f7(){txt.innerHTML = students.student7;};
function f8(){txt.innerHTML = students.student8;};
function f9(){txt.innerHTML = students.student9;};
function f10(){txt.innerHTML = students.student10;};
// so there are thousands of functions...
 <a class="k"  onClick="f1(); return false;" href="#">student1</a><br/>
<a class="k" onClick="f2(); return false;" href="#">student2</a><br/>
<a class="k" onClick="f3(); return false;" href="#">student3</a><br/>
<div id="txt"></div>

实际上我尝试过这个,认为它会起作用:

var stdnt = document.querySelectorAll(".k);
var x = stdnt.innerHTML;
var result = "";

if ( x === students[x] ){
x = students[x];
}
result = x;
function forAll (){
txt.innerHTML = result;
}

但它根本不起作用(我想这对于绝对的初学者来说是很自然的)。我非常需要一个想法。

最佳答案

您可以将其压缩为使用单个函数,并移交 anchor elemenet 的 innerHTML。该字符串可用作对象的访问器。

var txt = document.getElementById("txt");  
var students = {
student1: "english",
student2: "maths",
student3: "history",
student4: "geography",
student5: "science",
student6: "maths",
student7: "maths",
student8: "history",
student9: "french",
student10: "geography",
};

function f(key) {
txt.innerHTML = students[key];
};
<a class="k" onClick="f(this.innerHTML); return false;" href="#">student1</a><br/>
<a class="k" onClick="f(this.innerHTML); return false;" href="#">student2</a><br/>
<a class="k" onClick="f(this.innerHTML); return false;" href="#">student3</a><br/>
<div id="txt"></div>

关于javascript - 如何摆脱数千行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65278978/

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