Javascript onclick对象不是函数
所以我几个小时来一直在想这个问题 下面是我得到的错误: 我不明白是什么原因导致了错误,请见谅 这是我的代码,忽略smarty语法:Javascript onclick对象不是函数,javascript,jquery,Javascript,Jquery,所以我几个小时来一直在想这个问题 下面是我得到的错误: 我不明白是什么原因导致了错误,请见谅 这是我的代码,忽略smarty语法: <html> <head> <title>{$title}</title> {include file='header/header.tpl'} <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1
<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>
{$title}
{include file='header/header.tpl'}
{literal}
$(函数(){
函数登录(){
警报(“asdf”);
}
});
{/literal}
将登录移到就绪功能之外:
<script type="text/javascript">
$(function() {
function login() {
alert('asdf');
}
});
</script>
login
函数是在ready
事件处理程序中创建的,因此它只存在于该函数中
将其置于事件处理程序之外,使其存在于全局范围内,然后可以从单击事件处理程序调用它:
<script type="text/javascript">
function login() {
alert('asdf');
}
$(function() {
});
</script>
登录
不在范围内。在JavaScript中添加事件而不是在标记中。它怎么不在范围中?它看起来在作用域中除了作用域问题之外,login
函数和id=“login”
的输入都可以是login
的引用,因此您在这里会遇到名称冲突。请执行$(“#login”)。单击(login)
或向表单添加一个“submit”事件。我很好奇为什么要用jquery声明一个函数“准备好了吗“我不能打电话。我在jsbin中测试了它,你肯定是对的,但为什么会这样?@thomas:Javascript有函数作用域,这意味着你在函数中声明的变量只存在于该函数中。这也适用于函数,所以当你在另一个函数中声明一个函数时,它不能在它之外被访问。有什么办法吗?我只是好奇,显然没有必要用你建议的任何其他方式onClick=“$.login()”
对我不起作用,但是否还有其他方法可以访问存储在其他函数中的函数?@thomas:除非外部函数通过在全局变量中放置对内部函数的引用来公开内部函数,或者返回一个对它的引用,这样你就可以把返回值分配给一个全局变量。嗯……我不知道我明白我明白了。你介意为其中一个或两个提供一个例子吗?谢谢
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
<script type="text/javascript">
function login() {
alert('asdf');
}
$(function() {
});
</script>
<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>