我正在使用 JQuery Mobile 1.2 和 php 开发一个 Web 应用程序。在个人资料页面上,我有一个弹出窗口,要求用户确认注销。我想要做的是通过点击事件拦截该按钮,以通过 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>
最佳答案
您的个人资料页面上的custom.js实际上并未加载(更多内容见下文),因此当您绑定(bind)点击事件时,您的按钮在DOM中不存在,例如,您可以通过使用事件委托(delegate)来解决这个问题
$(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"
包装器中。您还可以通过在链接上使用 data-ajax="false"
属性(或 rel="external"
,如果它是不同的域)。
作为一个侧面,您应该考虑使用 .on从 jQuery 1.7 开始,.live
已被 depreciated 取代 .live
.
关于javascript - JQuery mobile v1.2 javascript 事件在弹出窗口中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730262/