jQuery里面的花哨的盒子ajax不工作——init问题

jQuery inside fancy box ajax not working -- init problems

本文关键字:工作 问题 ajax init 盒子 jQuery      更新时间:2023-09-26

这是我打开一个通过ajax加载页面的Fancybox的代码:

$('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;
    });
});

fancybox中的页面有一个表单,其中包含一个带有字符计数器的文本字段:

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

父页面通过header加载:

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

所以问题是这个字符计数器(和其他jQuery的东西,如验证,日期拾取器)不工作在Fancybox。如果页面没有Fancybox加载,或者通过Fancybox作为内联加载,则它们可以工作。

我明白这似乎是一个相当普遍的问题,但我尝试了所有的解决方案,但没有一个适合我。

我试过了

  • 使用不同的ajax页面id
  • 将字符计数脚本放在ajax页面的末尾(它甚至没有显示
  • )在Firebug
  • )
  • 将字符计数脚本作为success
  • 中的函数
  • 其他疯狂的迭代

这个问题似乎与ajax页面加载后重新初始化jQuery函数有关,因为这些元素在加载父页面时不存在。

有什么建议吗?

您需要重新绑定您的事件处理程序,一旦您在花式框内加载内容或使用JQuery。实时事件绑定机制。出现问题是因为事件处理程序试图绑定到尚未加载的DOM节点,因此需要做的是使用JQuery。live,它会将事件绑定到元素,即使它们还没有加载,或者当你的fancybox的内容已经加载时使用回调函数来绑定事件处理程序。

$(document).ready(function() {
    $('#ext_det').live('keyup', function() {
        // code to execute on keyup for element with id #ext_det    
    });
});