pageinit内的on click事件仅在页面刷新后有效 [英] on click event inside pageinit only works after page refresh

查看:70
本文介绍了pageinit内的on click事件仅在页面刷新后有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道那里有很多重复的问题,我检查了几乎所有问题,但是我找不到适合自己的解决方案.所以,这是我的问题:

I know there're a lot of duplicate questions out there, I checked almost all of them, but I just couldn't find a solution in my case. So, here's my problem:

我有一个横幅,它将显示在项目的每个页面上,横幅内有一个关闭按钮以关闭横幅,还有一个下载按钮,可将用户引导至应用商店以下载应用.我的横幅广告仅能正常工作,只是我必须刷新页面才能使这两个按钮正常工作.这是我的代码:

I have a banner which will show on every page of the project, inside the banner there's a close button to close the banner, and a download button which leads user to the app store to download the app. My banner works perfect only except I have to refresh the page to get these two buttons works. Here's my code:

$(document).on("pageinit", function () {
    $("#close").on("click", CloseBanner);
    $("#download").on("click", SetAppStorePath);
    //alert("pageinit");
});

function SetAppStorePath() {
    if (isIOS) {
        window.location = "https://itunes.apple.com/us/app/myapp/id.....";
}
    else if (isAndroid) {
    window.location = "https://play.google.com/store/apps/details?id=.....";
    }
}

function CloseBanner() {
    $('.banner').hide();
}

这是简化的html:

<div class="banner">
    <div class="container">
        <a id="close">&times;</a>
        <a id="download">Download</a>
    </div>
</div>

我做了一点测试,发现了一些棘手的问题:我在pageinit中添加了该警报,我注意到当我从A页跳到B页时,警报始终执行(意味着我的点击事件按钮始终被注册).但是当按钮起作用时,我看到页面A消失了,显示了空白页,显示了警报,然后显示了页面B,按钮起作用了.当它不起作用时,顺序是不同的,我仍然可以看到页面A,然后看到警报(现在我仍然可以看到页面A),然后它变为页面B,按钮不起作用.

I did a little test, and found something tricky: I added that alert inside pageinit, I noticed that the alert is always executed(means my button on click events are always registered) when I jump from page A to page B. But when the button works, I see page A is gone, blank page shows, alert shows, then page B shows, the buttons work. When it doesn't work, the order is different, I still can see page A, then I see alert(I still can see page A now), then it changes to page B, the buttons don't work.

所以看来,当在页面跳转后执行pageinit时,它可以工作,但是有时在页面跳转之前执行pageinit时,则它不起作用.

So seems that when pageinit executed after page jumped, it works,but sometimes pageinit executed before page jumped, then it doesn't work.

推荐答案

将其移至init外部,然后像

Move following outside of the init and change it like following

$(document).on("click","#close", CloseBanner);
$(document).on("click","#download", SetAppStorePath);

当页面初始化执行时,DOM未准备好.这就是它不绑定到关闭或下载元素的原因.这是克服这一问题的方法.您不需要这里的pageinit事件

when page init executes, DOM is not ready. that is the reason it is not binding to close or download elements. and this is the way to overcome that. you dont need pageinit event here

这篇关于pageinit内的on click事件仅在页面刷新后有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆