附加新元素后,jQuery函数不起作用

时间:2013-04-04 16:59:37

标签: jquery function

由于标题指的是这个函数似乎不适用于在document.ready函数之后附加的DOM元素。

我附加了一个新的.window元素,但此函数仍然只处理加载脚本时创建的.window元素。

如何对附加元素做出反应?

$(function() {
    // Change this selector to find whatever your 'boxes' are
    var windows = $("div.window");

    // Set up click handlers for each box
    windows.mousedown(function() {

        var tz = parseInt($('#toolbar').css( "z-index" ), 10 );
        $('#toolbar').css( "z-index", tz +1 )

        var el = $(this), // The box that was clicked
            max = 0;

        // Find the highest z-index
        windows.each(function() {
            // Find the current z-index value
            var z = parseInt( $( this ).css( "z-index" ), 10 );
            // Keep either the current max, or the current z-index, whichever is higher
            max = Math.max( max, z );
        });

        // Set the box that was clicked to the highest z-index plus one
        el.css("z-index", max + 1 );
        orderWindows(el);
    });
});

3 个答案:

答案 0 :(得分:4)

您将需要使用.on()的委托才能使动态添加的元素对事件做出反应。类似的东西:

$("#someparentelement").on("mousedown", "div.window", function() {
    // your code here
});

答案 1 :(得分:1)

在方法上使用jQuery:

$(function() {

    // Set up click handlers for each box
    $(document).on('mousedown', 'div.window',  (function() {

        var tz = parseInt($('#toolbar').css( "z-index" ), 10 );
        $('#toolbar').css( "z-index", tz +1 )

        var el = $(this), // The box that was clicked
            max = 0;

        // Find the highest z-index
        windows.each(function() {
            // Find the current z-index value
            var z = parseInt( $( this ).css( "z-index" ), 10 );
            // Keep either the current max, or the current z-index, whichever is higher
            max = Math.max( max, z );
        });

        // Set the box that was clicked to the highest z-index plus one
        el.css("z-index", max + 1 );
        orderWindows(el);
    });
});

答案 2 :(得分:0)

委派...是的...但是行话太多...

简单地说: 您仅在首次加载DOM时添加了事件侦听器。新元素没有附加事件监听器。


更新元素侦听器时的另一个重要想法是防止添加多个侦听器。 您需要使用:

$('div.window').off('<event>').on('<event>', function(){ ... });

这将防止事件在较旧的元素上多次出现。

请记住,$()返回jQuery对象列表。 $('div.window')返回它在DOM上找到的每个div.window。因此,它将为所有这些旧元素以及新创建的元素添加新的事件监听器。关闭它们,然后再打开它们,很好地防止了奇怪的功能。

使用bind()unbind()也是如此。

相关问题