从另一个页面显示隐藏的div onclick

时间:2012-08-23 05:53:05

标签: javascript html

我有两页。一个是

<html>
<head>
<script language="javascript">
  function toggleDiv(divid){
   if(document.getElementById(divid).style.display == 'none'){
  document.getElementById(divid).style.display = 'block';
}else{
  document.getElementById(divid).style.display = 'none';
 }
}
</script>
</head>
<body>

<a name="div1" href="javascript:;" onmousedown="toggleDiv('div1');"><p><b>Section 1</b>      </p></a>
<div id="div1" style="display:none">
Content for section 1.
</div>
<a name="div2" href="javascript:;" onmousedown="toggleDiv('div2');"><p><b>Section 2</b></p></a>
<div id="div2" style="display:none">
Content for section 2.
</div>
</body>
</html>

在其他页面上我有:

<html>
<head>
<title>Test</title>    
</script>
</head>
<body>
<a href="main.html#iv2">Section 2</a>
</div>

<script type="text/javascript">
if ( location.hash.length > 1 )
{
    toggleDiv( location.hash.substring(1) );
}
</script>
</body>
</html>

我想在这里实现的是,当我点击第二页上的“第2部分”时,主页面将打开并显示“div2”内容。上面的代码对我不起作用。

2 个答案:

答案 0 :(得分:1)

id

中缺少

<a href="main.html#div2">Section 2</a>

此脚本应位于第1页

<script type="text/javascript">
if ( location.hash.length > 1 )
{
    toggleDiv( location.hash.substring(1) );
}
</script>

希望这会有所帮助

这是您的第1页(main.html)的完整代码

<html>
<head>

</head>
<body>

<a name="div1" href="javascript:;" onmousedown="toggleDiv('div1');"><p><b>Section 1</b>      </p></a>
<div id="div1" style="display:none">
Content for section 1.
</div>
<a name="div2" href="javascript:;" onmousedown="toggleDiv('div2');"><p><b>Section 2</b></p></a>
<div id="div2" style="display:none">
Content for section 2.
</div>
</body>

<script type="text/javascript">
if ( location.hash.length > 1 )
{
    toggleDiv( location.hash.substring(1));
}
 function toggleDiv(divid){
  alert(divid);
   if(document.getElementById(divid).style.display == 'none'){
  document.getElementById(divid).style.display = 'block';
}else{
  document.getElementById(divid).style.display = 'none';
 }
}
</script>
</html>

答案 1 :(得分:0)

你不能调用Javascript函数那样......那就行不通了......你需要在页面的onLoad事件中调用函数...比如

<body onload="toggleDiv('div2')"> 
</body>

<强>否则

打开Popup并使用“Window opener”属性。查看此链接http://www.w3schools.com/jsref/prop_win_opener.asp

相关问题