jQuery live()无法正常工作..可能做错了吗? [英] jQuery live() not working.. probably doing it wrong?

查看:100
本文介绍了jQuery live()无法正常工作..可能做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分页的项目列表,每个项目都有一个与之相关的复选框.

I have a paged list of items, each with a checkbox associated with it.

如果单击复选框,则会将该复选框的ID写入Cookie.重新加载页面时,我要重新选中所有先前选择的复选框.

If I click a checkbox, I write that checkbox's id to a cookie. When the page reloads, i want to re-check all the previously selected checkboxes.

使用以下代码可以正常工作:

This works fine with the following code:

$('.fund-compare-check-box').each(function () {
    var cookie = getCookie("fund_basket").split("|");

    // re-check all check boxes
});

我遇到的问题是,当我加载结果的下一页时.上面的代码仅在DOM准备就绪时运行.

The problem I have with this, is when I load the next page of results. The code above only runs when the DOM is ready.

我认为我可以通过使用.live()而不是.each()来解决此问题,如下所示:

I thought I could fix this by using .live() instead of .each(), as follows:

$('.fund-compare-check-box').live('each', function () {
    var cookie = getCookie("fund_basket").split("|");

    // re-check all check boxes
});

但是当我使用它时,什么也没有发生.我做错了吗?任何指针将不胜感激!

but when I use this, nothing happens at all. Am I doing this wrong? Any pointers would be much appreciated!

推荐答案

live用于将事件处理程序绑定到当前可能存在或可能不存在的元素.第一个参数是事件类型.您的代码将函数绑定到与选择器匹配的元素上的each事件.显然,each事件不存在.

live is for binding event handlers to elements that may or may not currently exist. The first argument is the event type. Your code binds a function to the each event on elements that match your selector. Obviously, the each event does not exist.

您可能希望在每个AJAX查询之后执行代码(我假设您的元素是通过AJAX添加的).在这种情况下,您可能想使用ajaxComplete:

You probably want your code to be executed after every AJAX query (I'm presuming your elements are being added through AJAX). If this is the case, you may like to use ajaxComplete:

$(document).ajaxComplete(function() {
    $('.fund-compare-check-box').each(function () {
        var cookie = getCookie("fund_basket").split("|");

        // re-check all check boxes
    });
});

如果您以不同的方式添加内容,则每次添加内容时,您都必须找出某种方法来调用该函数.

If your content is added in a different way, you'll have to figure out some way to call that function each time the content is added.

这篇关于jQuery live()无法正常工作..可能做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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