我正在使用JQuery Mobile 1.2和php开发一个web应用程序。在profile页面,我有一个弹出窗口,要求用户确认注销。我要做的是用一个click事件截取该按钮,以通过ajax请求处理注销。
我的所有项目页面都包含一个custom.js文件。应用程序将加载到“帐户”页中。我知道它是通过ajax导航加载和工作的。
当我在custom.js中包含此代码时:
$("#perfil").live('pageshow',function(event){
alert('This page was just enhanced by jQuery Mobile!');
});
显示配置文件页时我会收到警报。问题是点击功能。
当我包括这个:
$("#perfil").live('pageshow',function(event){
alert('This page was just enhanced by jQuery Mobile!');
$('#logoutButton').click(function(){
$('#output').html('Logging Out...');
$.get("api/logout",function(data){
if(data.success) {
window.location = "index"
}
else{
$('#output').html('Logout failed. Try again');
}
}, "json");
});
});
这种行为很奇怪。当我从主页导航到配置文件页时,会收到警报。但是按钮没有反应。但是,当我刷新(或最初从配置文件页面加载应用程序)时,按钮的行为正确,并运行javascript注销功能。
下面是html按钮的代码:
<a id="logoutButton" data-role="button" data-icon="check"
data-inline="true" data-theme="e">Si, finalizar.</a>
最佳答案
您的配置文件页上的Cuth.js没有被加载(更多的是在下面),因此当您绑定了单击事件时,DOM中不存在按钮,您可以通过使用事件委托来绕过这个问题。
$(document).on('click', '#logoutButton', function(){
$('#output').html('Logging Out...');
$.get("api/logout",function(data){
if(data.success) {
window.location = "index"
}
else{
$('#output').html('Logout failed. Try again');
}
}, "json");
});
现在之所以没有加载custom.js,是因为在jQuery Mobile中加载页面时,默认情况下default behavior是通过ajax加载
data-role="page"
div并将其附加到当前页面的DOM。要认识到的重要一点是,只有div页面被加载,而不是该页面上的任何其他资源。如果您希望加载单独页面上的自定义脚本,则需要将其包含在div
data-role="page"
包装器中。您还可以告诉JQM在没有ajax的情况下通过在链接上使用data-ajax="false"
属性来完全加载一个页面(如果它是一个不同的域,则使用rel="external"
属性)。作为一个侧重点,您应该考虑使用.on而不是
.live
,因为jQuery 1.7.live
已经depreciated。关于javascript - jQuery Mobile v1.2 JavaScript事件在弹出窗口中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13730262/