我只能通过创建 2 个单独的事件来让按钮工作:
$('#loginSubmit').click (function ()
{
var userName = $('#userName').val();
var password = $('#password').val();
event.preventDefault();
$.ajax({
type: "POST",
url: "auth.php",
data:"userName="+userName+"&password="+password,
success: function(result)
{
//$('#mainBody').html(result);
window.location.replace('chooseGroup.php');
}
})
});
$('input').keypress(function(event)
{
if (event.which == 13) {
var userName = $('#userName').val();
var password = $('#password').val();
event.preventDefault();
$.ajax({
type: "POST",
url: "auth.php",
data: "userName="+userName+"&password="+password,
success: function(result)
{
//$('#mainBody').html(result);
window.location.replace('chooseGroup.php');
}
})
}
})
});
html:
<div class='Lrow'><input type='button' id='loginSubmit' value='Login'></div>
我知道可能有更好的方法。我很想听。无论如何,如果我使用 mozilla 浏览器,则按键功能中的“事件”是未定义的。这在 Chrome 中工作得很好。有什么想法吗?
最佳答案
将公共(public)代码放入函数中。
var mySubmitFunction (event) {
//the code
}
$('#loginSubmit').on("click", mySubmitFunction );
$('input').keypress(function(event){
if (event.which == 13) {
mySubmitFunction(event);
}
});
<小时/>
但是有一种更好的方法,无需监听点击/输入键。更好的方法是让表单做它想做的事。
当您输入正确时,表单将在输入时提交。您只需添加一个提交按钮和一个 onsubmit 事件。您在那里取消提交并进行 Ajax 调用。将按钮类型设置为提交,它应该可以工作。好处是如果 JS 被禁用,表单仍然会提交到服务器。
$("#YourForm").on("submit", function(event){ /* code here */ });
关于javascript - 单击或按 Enter 键即可使用的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21193463/