2014-08-31 86 views
0

所以我一直试图弄清楚这一点了几个小时的Javascript的onclick对象不是一个函数

下面是我得到的错误:

error

我不明白是什么导致错误,任何见解将不胜感激!

这里是我的代码,忽略Smarty的语法:

<html> 
    <head> 
     <title>{$title}</title> 
     {include file='header/header.tpl'} 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> 
    </head> 
    <body> 
    <div class="container" style="padding-top: 5%;"> 
     <form action="" method="POST"> 
      <center> 
       <img src="" style="height: 70px;"> 
      </center> 
      <div class="form-signin"> 
       <input type="email" class="form-control" style="font-size: 10pt;" id="email" placeholder="Email Address" required autofocus> 
       <input type="password" class="form-control" style="font-size: 10pt;" id="password" placeholder="Password" required> 
       <input type="submit" class="btn btn-warning btn-sm" value="Login" data-loading-text"Login" id="login" onClick="login();" style="outline: none;"> 
      </div> 
     </form> 
    </div> 
    {literal} 
    <script type="text/javascript"> 
     $(function() { 
      function login() { 
       alert('asdf'); 
      } 
     }); 
    </script> 
    {/literal} 
    </body> 
</html> 
+1

'login'不在范围内。在JavaScript_中不添加标记中的事件_in。 – elclanrs 2014-08-31 20:30:03

+0

它不在范围内?它看起来在范围 – user3681580 2014-08-31 20:33:45

+0

除了范围问题,'login'函数和'id =“login”'的输入都可以用'login'引用,所以你最终在这里遇到名称冲突。 – haim770 2014-08-31 20:34:10

回答

2

移动登录就绪功能之外:

<script type="text/javascript"> 
    $(function() { 
     function login() { 
      alert('asdf'); 
     } 
    }); 
</script> 

要:

<script type="text/javascript"> 
     function login() { 
      alert('asdf'); 
     } 
</script> 

问题是登录只存在于ready函数范围内。实施例

function say() { 

    function hello() { 
     alert("hello"); 
    } 

    // call hello inside the say scope 
    hello(); // this displays the alert 
} 


say(); // this will show the alert 

hello(); // error function is not defined. because it is out of scope 
0

login功能被ready事件处理程序内创建的,所以它仅该函数内部存在。

把它的事件处理程序之外,使其在全球范围内存在,那么你可以从Click事件处理程序调用它:

<script type="text/javascript"> 

    function login() { 
     alert('asdf'); 
    } 

    $(function() { 
    }); 

</script> 

考虑使用,而不是点击的submit活动形式事件在按钮上。然后,如果用户通过在字段中按Enter提交表单,它也将起作用。还考虑在脚本中而不是在标记中绑定事件:

<script type="text/javascript"> 

    $(function() { 

     $('form').submit(function(e){ 
     e.preventDefault(); // if you want to stop the submit and do something else' 
     alert('asdf'); 
     }); 

    }); 

</script> 
+0

我很好奇为什么用jquery“ready”声明的函数不能被调用。我用jsbin测试过,你说得对,但为什么呢? – 1252748 2014-08-31 20:47:57

+0

@thomas:Javascript有函数作用域,这意味着你在函数中声明的变量只存在于函数内部。这也适用于函数,所以当你在另一个函数中声明一个函数时,它不能在其外部访问。 – Guffa 2014-08-31 21:23:24

+0

有没有办法解决这个问题?我只是好奇,显然没有必要以任何其他方式做比你的建议。 'onClick =“$。login()”'对我来说不起作用,但是无论如何要访问存储在其他函数中的函数吗? – 1252748 2014-09-01 18:08:20

相关问题