Javascript 未捕获引用错误:未定义reg
我正在尝试使用jquery、ajax和php构建一个登录和注册表单。但是当我按下注册按钮时,我发现了这个错误Javascript 未捕获引用错误:未定义reg,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我正在尝试使用jquery、ajax和php构建一个登录和注册表单。但是当我按下注册按钮时,我发现了这个错误 <!-- Formular for signing up --> <form method="post"> <div class="form-group"> <label> Username </label> <input type="text" class="form-contr
<!-- Formular for signing up -->
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub">
</div>
<button type="button" onClick='reg' class="btn btn-success">Sign up!</button>
</form>
使用onClick='reg()'
。您需要在这里进行函数调用,这是正确的语法
更新:您还需要将函数移到$(document).ready(function(){})
使用onClick='reg()'
。您需要在这里进行函数调用,这是正确的语法
更新:您还需要将函数移到
$(document).ready(function(){})
从onXYZ
属性事件处理程序调用的函数必须是全局函数(这是不使用它们的几个原因之一)。您的reg
函数不是全局函数,它很好地包含在ready
回调中(这是一件好事)™, 全局名称空间已经非常拥挤,并且容易发生冲突)
另外,onClick='reg'
不起作用,它必须是onClick='reg()'
相反,通过以下方式动态连接reg
:
注册!
及
$(文档).ready(函数(){
$(“#btn reg”)。在(“click”,reg)//上,从onXYZ
属性事件处理程序调用的函数必须是全局函数(这是不使用它们的几个原因之一)。您的reg
函数不是全局函数,它很好地包含在ready
回调中(这是一件好事)™, 全局名称空间已经非常拥挤,并且容易发生冲突)
另外,onClick='reg'
不起作用,它必须是onClick='reg()'
相反,通过以下方式动态连接reg
:
注册!
及
$(文档).ready(函数(){
$(“#btn reg”)。打开(“单击”,reg);//不要将reg
函数放入$(文档)。准备好函数。或者使用更标准的方式附加事件,如$(“.btn success”)。单击(reg);
或类似的内容。定义reg()
在文档之外。就绪
处理程序,因此它在onclick
属性的范围内。更好的是-使用Javascript附加事件。这更好,因为它删除了丑陋的onclick
属性,更好地分离关注点,并且不会出现范围问题。不要将reg
f$(文档)中的函数。就绪
函数。或使用更标准的方式(如$(“.btn success”))附加事件。单击(reg);
或类似内容。定义reg()
在文档之外。ready
处理程序,因此它在onclick
属性的范围内。更好的是-使用Javascript附加事件。这更好,因为它删除了丑陋的onclick
属性,更好地分离关注点,并且不会出现范围问题。虽然这是正确的语法,reg()
函数未在正确的范围内定义,因此仅此一项仍然不起作用。@Rorymcrossan在文档准备好后该函数不起作用吗?@RejithRKrishnan:见我的答案。它必须是全局的。OP不是全局的。@t.J.Crowder得到了它。我没有真正思考。:)我建议不要创建更多全局变量
函数未在正确的范围内定义,因此仅此一项仍然不起作用。@Rorymcrossan在文档准备好后函数不起作用吗?@RejithRKrishnan:请看我的答案。它必须是全局的。OP不是全局的。@t.J.Crowder明白了。我不是真的在想。:)我不建议创建更多全局的。
$(document).ready(function () {
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('class/callingClass.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});
<button type="button" id="btn-reg" class="btn btn-success">Sign up!</button>
<!-- Removed onClick, added id -->
$(document).ready(function () {
$("#btn-reg").on("click", reg); // <== Added
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('class/callingClass.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});