简体   繁体   English

定义的功能为“未定义”

[英]Defined function is “Not defined”

The following function is defined in the head tags of my page. 我页面的head标签中定义了以下功能。

<script type="text/javascript">     
$(document).ready(function(){

function greenTab(input){
    if ($input === 'second') {
        $('#green').css({'display':'none'});
        $('#2ndgreen').css({'display':'initial'});
    } else if ($input === 'first') {
        $('#2ndgreen').css({'display':'none'});
        $('#green').css({'display':'initial'});
    }
}   
});
</script>

And I call it in this fashion: 我这样称呼它:

<div class="container">
    <ul class="nav nav-pills">
        <li class="active" onclick="greenTab('first')"><a>1st Green</a></li>
        <li class="active" onclick="greenTab('second')"><a>2nd Green</a></li>                         
    </ul>
</div>

The issue: Firebug says the function is not defined. 问题:Firebug说该函数未定义。 Desired outcome: For the function to be defined. 所需结果:用于定义功能。

Why is it broken: 为什么会坏:

The onclick attribute expects functions to be exposed on global scope. onclick属性期望函数在全局范围内公开。

Because you have defined greenTab within the ready function, it is defined within the scope of that function, not on global scope, so it can't be found on the global scope. 因为您已经在ready函数中定义了greenTab ,所以它是在该函数的范围内定义的,而不是在全局范围内定义的,因此无法在全局范围内找到它。

How to fix it: 解决方法:

Either: 要么:

  1. Expose it globally. 在全球范围内公开。 (Don't do this) (不要这样做)
  2. Add your event listeners through JS, not HTML (Probably do this) 通过JS(而不是HTML)添加事件监听器(可能是这样做)

Since you're using jQuery, you should add your event handlers like this: 由于您使用的是jQuery,因此应添加如下的事件处理程序:

$('some selector').click(function () {
    greenTab('first');
});

What some selector should be right now is '.container ul li:nth-of-type(1)' , but I would suggest adding something to those elements to select on them better, eg: 现在一些选择器应该是'.container ul li:nth-of-type(1)' ,但是我建议在这些元素上添加一些内容以便更好地选择它们,例如:

<div class="container">
    <ul class="nav nav-pills">
        <li class="active first-green"><a>1st Green</a></li>
        <li class="active second-green"><a>2nd Green</a></li>                         
    </ul>
</div>

And then your first selector should just be: 然后您的第一个选择器应该是:

$('.first-green').click(function () {
    greenTab('first');
});

You will need to do the same for the second click handler as well. 您还需要对第二个单击处理程序执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM