HTML代码<a> Both href and onclick

时间:2015-08-24 19:13:01

标签: javascript jquery html css

I'm working on this project and I'm really stuck on 1 thing: I would like to make a submenu with all sub-pages in one html file.

Whenever I use both href and onclick it does not work.

It only works when I change the href into "#", but that would make the page inaccessible from other pages.

Please note that changing the return value of the function does not help.

Thanks so much in advance!

Here is my HTML:

<script>
function show(shown, hidden, hidden2) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  document.getElementById(hidden2).style.display='none';
  return true;
}
</script>

<ul>                
<li><a href="../info/index.html" onclick="return show('Page1','Page2','ṕage3');">Doelstelling</a></li>
<li><a href="../info/index.html" onclick="return show('Page2','Page1','ṕage3');">Bestuur</a></li>
<li><a href="../info/index.html" onclick="return show('Page3','Page1','ṕage2');">Lid worden</a></li>
</ul>

<div id="Page1" style="display:none">
<a href="#" onclick="return show('Page2','Page1','ṕage3');">Bestuur</a></br>
<a href="#" onclick="return show('Page3','Page1','ṕage2');">Lid worden</a>   </br>
<p>

text

</p>

</div></br>

<div id="Page2" style="display:none">
<a href="#" onclick="return show('Page1','Page2','ṕage3');">Doelstelling</a>    </br>
<a href="#" onclick="return show('Page3','Page1','ṕage2');">Lid worden</a></br>
<p>

text

</div></br>
  <div id="Page3" style="display:none">
<a href="#" onclick="return show('Page1','Page2','ṕage3');">Doelstelling</a>  </br>
<a href="#" onclick="return show('Page2','Page1','ṕage3');">Bestuur</a></br>
    <p>
text
 </p>

</div></br>

Thanks again.

4 个答案:

答案 0 :(得分:2)

return false;无法帮助您,因为在此代码行之前会触发错误。

查看您的show函数调用:您将'ṕage3'作为第三个参数传递,然后执行document.getElementById(hidden2).style.display = ...。但是你没有id =&#34;ṕage3&#34;的元素。

'ṕage3'替换为'Page3',这应该可以解决问题

答案 1 :(得分:0)

您需要在OnClick中返回false。 由于您在onclick中调用show,因此返回false而不是true。

<script>
function show(shown, hidden, hidden2) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  document.getElementById(hidden2).style.display='none';
  return false;
}
</script>

当用户点击锚点(标记)时,它将首先执行onclick。如果onclick返回false,它将停止。如果onclick返回true,则它将继续使用默认行为并将窗口位置更改为href属性的值。

答案 2 :(得分:0)

您需要使用event.preventDefault();

禁用JavaScript中的默认事件处理

答案 3 :(得分:0)

&#13;
&#13;
$("a").click(function()
{
  alert(1);
  return false;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com">Text</a>
&#13;
&#13;
&#13;

2015年不要使用onclick

相关问题