Javascript链接停止工作,无法弄清楚原因

Eri*_*man 0 html javascript jquery

我有一个网站使用js在两个不同的导航菜单之间切换.它一直工作到一周前左右,我无法弄清楚原因.想知道这里是否有人可以向我指出我没有看到的东西.

这是我的标记:

<div class="catMenu">
    <a href="javascript:showonlyone('newboxes1');">Works</a>
</div>

<div class="newboxes" id="newboxes1" style="display:block;" >
    ...the 1st menu
</div>

<div class="catMenu2">
    <a href="javascript:showonlyone('newboxes2');" >About</a>
</div>

<div class="newboxes" id="newboxes2"  style="display:none;">
    ...the 2nd menu
</div> 
Run Code Online (Sandbox Code Playgroud)

这是我的js:

$(document).ready(function() {
    function showonlyone(thechosenone) {
       $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).show();
          }
          else {
               $(this).hide();
          }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

当我使用firebug查看我的控制台时,出现以下错误:

ReferenceError: showonlyone is not defined
Run Code Online (Sandbox Code Playgroud)

但由于我对js缺乏了解,我不完全确定如何解决这个问题.

任何人都能解释一下吗?

hai*_*770 7

如果您要showonlyone使用href="javascript:showonlyone()"它来调用该函数,则必须在全局范围内定义它,目前它已在document.ready()函数内定义.

您还可以使用window关键字显式公开它:

$(document).ready(function() {
    window.showonlyone = function showonlyone(thechosenone) {
       $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).show();
          }
          else {
               $(this).hide();
          }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)