更新时间:2023-11-28 22:37:58
您在委派事件绑定内部发生了标准事件绑定.这意味着每次外部事件触发时,内部绑定都将被绑定.
You've got a standard event binding happening inside of a delegated event binding. That means that the inner-binding will be bound every time the outer-event fires.
因此,基本上,每次pagebeforeshow
为任何伪页面触发时,您都将重新绑定您的tap
事件处理程序.每次导航到另一个页面时,您都会创建另一个内部绑定,因此会收到多个警报.
So basically you're re-binding your tap
event handler each time the pagebeforeshow
fires for any pseudo-page. Each time you navigate to another page you're creating another inner-binding so you're getting multiple alerts.
一个好的解决方法是为pageinit
页面事件创建一个委托事件处理程序,并在该事件处理程序中进行内部绑定. pageinit
事件每个伪页面仅触发一次,因此您将不必继续添加不必要的事件处理程序.
A good fix is to create a delegated event handler for the pageinit
page-event and do the inner-binding in that event handler. The pageinit
event only fires once per pseudo-page so you won't keep adding more event handlers unnecessarily.
例如:
$(document).on('pageinit', '.ui-page',function(){
var db = window.openDatabase("mydb", "1.0", "MyDB", 1000000),
url = window.location.href,
filename = url.substring(url.lastIndexOf('/')+1);
switch (filename) {
case "index.html":
$("#add").tap(function(e){
if ($("#info").val() == "") {
navigator.notification.alert("The info cannot be blank!", function(){}, "Error", "Okay, got it!");
} else {
db.transaction(addToDb, errorCB, addedToDb);
}
});
break;
case "sample.html":
break;
}
});
您会注意到,我将.on()
用作委派的事件处理程序,而不是已贬值的.live()
.
You'll notice I used .on()
for my delegated event handler instead of the depreciated .live()
.