尝试增强功能时遇到麻烦。我刚刚用Javascript进行了介绍,所以我希望我会找到很多人来帮助我变得更好。 :)
这是我想要做的一个例子:
<script type="text/javascript">
var title1 = "<h2>Cisco</h2>";
var summary1 = "<p>Cool class</p>";
var Register1 = "<button>Register</button>";
var title2 = "<h2>Whatever title</h2>";
var summary2 = "<p>Whatever Summary</p>";
var Register2 = "<button>Whatever Register</button>";
//But I have to create about 10 functions if I do it this way...
function course1()
{
document.getElementById('courseTitle').innerHTML = title1;
document.getElementById('courseSummary').innerHTML = summary1;
document.getElementById('courseRegister').innerHTML = Register1;
}
function course2()
{
document.getElementById('courseTitle').innerHTML = title2;
document.getElementById('courseSummary').innerHTML = summary2;
document.getElementById('courseRegister').innerHTML = Register2;
}
//So I taught about doing it with parameters so I could only build one function.
//For some reason it doesn't work.
//Here is how my improved function idea looks
function course(x)
{
document.getElementById('courseTitle').innerHTML = title+x;
document.getElementById('courseSummary').innerHTML = summary+x;
document.getElementById('courseRegister').innerHTML = Register+x;
}
//And here is how you would call them
<input type"button" value="course1" onclick="course(1)">
<input type"button" value="course1" onclick="course(2)">
我将不胜感激任何帮助!谢谢。
答案 0 :(得分:4)
您可以使用数组来保存数据:
var data = [{
title: "<h2>Cisco</h2>",
summary: "<p>Cool class</p>",
Register: = "<button>Register</button>"
},{
title: "<h2>Whatever title</h2>",
summary: "<p>Whatever Summary</p>",
Register: "<button>Whatever Register</button>"
}];
然后只需将索引传递给您的函数:
function course( index ) {
document.getElementById('courseTitle').innerHTML = data[index].title;
document.getElementById('courseSummary').innerHTML = data[index].summary;
document.getElementById('courseRegister').innerHTML = data[index].Register;
}
答案 1 :(得分:2)
你需要使用数组
var globalCourses = [['cisco','cool class','register'],['whatever','whatever sum','whatever reg']];
function course(i){
var title = globalCourses[i][0];
var summary = globalCourses[i][1];
var register = globalCourses[i][2];
//do what you need with this
document.getElementById('courseTitle').innerHTML = title;
//etc
}
因此,只要您想到一组参数相同的数据,就可以使用数组或对象数组。
您还可以执行以下操作:
var globalCourses = [{title:"title",summary:"sum",register:"register"},{title:"another title",summary:"another sum",register:"another register"}];
function course(i){
var title = globalCourses[i].title;
var summary = globalCourses[i].summary;
//etc
}