我修改了我在jsfiddle上找到的这个javascript代码。我的目标是在单击链接时显示表格,当单击其他链接时,它会显示不同的表格并隐藏上一个表格。这是我的代码:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled Document</title>
<script>
var elem=document.getElementById("loginTable");
var hide = elem.style.display =="none";
var elem2=document.getElementById("loginTable2");
var hide2 = elem2.style.display == "none";
function toggleTable(){
if (hide){
elem.style.display="table";
elem2.style.display="none";
}
else{
elem.style.display="none";
}
}
function toggleTable2(){
if (hide2){
elem2.style.display="table";
elem.style.display="none";
}
else{
elem2.style.display="none";
}
}
</script>
</head>
<body>
<a href="#" id="loginLink" onclick="toggleTable();return false" >Business Cards</a>
<table id="loginTable" border="1" align="center" style="display:none">
<tr>
<td>
Business card table
</td>
</tr>
</table>
<a href="#" id="loginLink" onclick="toggleTable2();return false" >Letterheads</a>
<table id="loginTable2" border="1" align="center" style="display:none">
<tr>
<td>
Letterhead table
</td>
</tr>
</table>
</body>
</html>
它适用于jsfiddle,但当我将它放在我的HTML页面上时,它将无法运行。
有什么建议吗?
此外,我不了解JavaScript,我只修改了它,它在jsfiddle上运行,但不是我的HTML页面。
答案 0 :(得分:1)
当你的脚本加载它没有找到DOM元素,因此它不能正常工作
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<a href="#" id="loginLink" onclick="toggleTable();return false" >Business Cards</a>
<table id="loginTable" border="1" align="center" style="display:none">
<tr>
<td>
Business card table
</td>
</tr>
</table>
<a href="#" id="loginLink" onclick="toggleTable2();return false" >Letterheads</a>
<table id="loginTable2" border="1" align="center" style="display:none">
<tr>
<td>
Letterhead table
</td>
</tr>
</table>
<script>
var elem=document.getElementById("loginTable");
var hide = elem.style.display =="none";
var elem2=document.getElementById("loginTable2");
var hide2 = elem2.style.display == "none";
function toggleTable(){
if (hide){
elem.style.display="table";
elem2.style.display="none";
}
else{
elem.style.display="none";
}
}
function toggleTable2(){
if (hide2){
elem2.style.display="table";
elem.style.display="none";
}
else{
elem2.style.display="none";
}
}
</script>
</body>
</html>
如果你想在head部分使用脚本,你需要编写window.onload函数
<script>
window.onload=function(){
// your JS code
}
</script>