开发者

jQuery inside fancy box ajax not working -- init problems

This is my code to open a Fancybox that loads a page via ajax:

$('tr.record').click(function() {
    var record_id = $(this).attr("id");
    var link = 'http://' + window.location.hostname + '/expenses/expenses_edit/' + record_id;
    $.fancybox({
        'transitionIn': 'fade',
        'transitionOut': 'none',
        'type': 'ajax',
        'href': link,
        'onClosed': function() {
            parent.location.reload(true);
        }
    });
    $.bind("submit", function() {

        $.fancybox.showActivity();

        $.ajax({
            type: "POST",
            cache: false,
            data: $(this).serializeArray(),
            success: function(data) {
                $.fancybox(data);
            }
        });
        return false;
    });
});

The page inside the fancybox has a form including a text field with char counter:

<form>
...

<textarea name="exp_det" cols="90" rows="12" id="exp_det"></textarea>
<span id="charLeft">150</span> characters left

</form>

The parent page loads this via header:

$('#ext_det').keyup(function() {
    var len = this.value.length;
    if (len >= 150) {
        this.value = this.value.substring(0, 150);
    }
    $('#charLeft').text(150 - len);
});

So t开发者_如何转开发he issue is that this char counter (and other jQuery stuff like validation, datepicker) don't work inside the Fancybox. They do work if the page is loaded without Fancybox, or if it is loaded via Fancybox as inline.

I understand this seems to be a reasonably common question, but I tried all solutions and none worked for me.

I've tried

  • using diferent IDs for the ajax page
  • placing the char count script at the end of ajax page (it didn't even show
  • on Firebug)
  • placing the char count script as a function within success
  • other crazy iterations

The problem seems related to re-init'ing the jQuery functions after the ajax page has loaded, since these elements were not there when the parent page was loaded.

Any suggestions?


You need to either rebind your event handlers once you have loaded content inside the fancy box or use the JQuery.live event binding mechansim. Your problem is occuring because your event handlers are trying to bind to DOM nodes that are not yet loaded, so what you need to do is either use the JQuery.live, which will bind events to elements even when they have not yet loaded OR use a callback function when your content of your fancybox has loaded to bind the event handlers.

$(document).ready(function() {
    $('#ext_det').live('keyup', function() {

        // code to execute on keyup for element with id #ext_det    

    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜