![](/img/trans.png)
[英]Why isn't my javascript onclick event triggered on the first click?
[英]Why isn't this alert displayed on first click?
我创建了一个按钮。 当我单击按钮时,我希望它运行一个PHP文件并显示警报。 这是我要尝试的:HTML:
<button id="testid" style="height:20px; width: 50px; cursor: pointer" onclick="logoutfunc()">Logout</button>
JavaScript:
function logoutfunc() {
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
}
logoutt.php
<?php
$a="Hello";
echo $a;
?>
现在的问题是,当我第一次单击按钮时,它不显示警报。 但是当我再次单击它时,它两次显示相同的警报。 当我再次单击它时,它会发出3次警告,依此类推。 我写错什么了?
您将单击处理程序绑定到内联事件处理程序中,因此,在第一次附加事件处理程序时单击按钮。 因此,它第二次工作。
摆脱内联单击处理程序。 只是使用jQuery绑定事件处理程序
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
您为什么一次又一次绑定同一事件?
....onclick="logoutfunc()"...
从HTML删除此部分,然后在javascript中删除围绕文档就绪处理程序的函数。
$(document).ready(function(){
$("#testid").click(function(){
// your ajax code.
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.