0

如果在替换对象后对其进行检查,是否有办法继续检查它

这说明了我遇到的问题

http://jsfiddle.net/nr6eA/

一旦元素被替换,更改功能就不会再次触发,虽然我很清楚为什么会发生这种情况,但我不知道如何解决这个问题。

我有很多复选框,并且在替换它们时为每个复选框添加一个脚本似乎不是最好的主意。

有没有办法在 ajax 更新时重新初始化 jquery 函数?

4

1 回答 1

1

您需要事件委托。为此,您可以使用on()jQuery 1.7+,如下所示:

对于.on()

$(document).ready(function() {
    $('#f').on('change', ' input:checkbox', function() {
        $('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
        $(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
    });
});​

但是,你的小提琴显示jQuery 1.6.2。在这种情况下,您可以使用live()delegate()

对于live()

$(document).ready(function() {
    $('#f input:checkbox').live('change', function() {
        $('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
        $(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
    });
});​

对于delegate()

$(document).ready(function() {
    $('#f').delegate('input:checkbox', 'change', function() {
        $('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
        $(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
    });
});​

但是如果你可以使用.on()jQuery 1.7+ 会更好。

于 2012-08-11T04:08:48.153 回答