使用load()函数加载页面后,on('click')jquery无法正常工作

问题描述:

使用Cookie来了解要在DIV中加载哪个页面

Is use a cookie to know which page to load inside my DIV

if($.cookie('logged') == null){
    $('#auction-form').load('pages/login.php');
}else{
    $('#auction-form').load('pages/bid.php');
}

但是在login.php页面中,我还有另一个链接,它将触发另一个不起作用的load()函数.

But inside the login.php page, I have another link that would trigger another load() function which is not working.

$('.register-btn').on('click',function(){
    $('#auction-form').load('pages/register.php');
});

.register-btn类是一个链接,应触发上面的功能.我知道这可能是因为加载login.php页面时,它不在DOM中,所以看不到.register-btn.我如何在从load()函数加载的页面上委派脚本?

The .register-btn class is a link which should trigger the function above. I know this might be something that it's because when the login.php page is loaded, it's not in the DOM so the .register-btn can't be seen. How I could delegate the script on a page that is loaded from a load() function ?

使用事件委托通过 .on()

$(document).on('click','.register-btn',function(){

代替

$('.register-btn').on('click',function(){

由于.register-btn不驻留在DOM(动态元素)上,因此无法直接绑定事件.

Since .register-btn does not reside on the DOM(dynamic element), you cannot bind the event directly.

对于动态元素,语法为:

For dynamic elements, the syntax is:

$(parentselector).on('event', 'selector', yourFunction)

请注意,parentselector必须是Non-dynamic always DOM present element

Note that parentselector needs to be a Non-dynamic always DOM present element