To show which course a student is taking, I wrote these simple lines, click the student and see the course, but there seems to be thousands of code lines since I should list so many students and courses. Is there a way to write a single function to get the value of the object instead of writing a seperate function for each click?
//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>
Actually I tried this, reasoning that it would work:
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;
}
But it doesn't work at all (I guess it's natural for an absolute beginner). I badly need an idea.