2013-04-04 40 views
0

由於標題引用此函數似乎不適用於在document.ready函數之後附加的DOM元素。追加新元素後,jQuery函數不起作用

我附加了一個新的.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); 
    }); 
}); 
+0

複製大的時間。有關答案,請參見[jQuery \'點擊','綁定','live','委託','觸發器'和\'on \'函數之間的區別(舉例) ?](http://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-trigger-and-on) – 2013-04-04 17:02:30

+1

如果我理解正確,也許你可以使用jquery函數.on (),這樣mousedown事件仍然會觸發新添加的元素。 – KiiroSora09 2013-04-04 17:05:16

+0

@JanDvorak我看不到這是另一個問題的重複。我無法找到解決方案。甚至連Stackoverflow都沒有提供有關類似問題的信息。我很抱歉,它讓你困擾不已。 – Dimser 2013-04-04 17:13:25

回答

4

您將需要使用具有.on()的委派才能使動態添加的元素對事件作出反應。喜歡的東西:

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

請注意,'document'始終作爲父母使用 – 2013-04-04 17:04:24

+3

@JanDvorak:當然,'.on()'替換'.live()'的主要原因之一就是你*不*必須這樣做。 – 2013-04-04 17:06:16

+0

主要原因是'live'執行選擇並丟棄結果。 – 2013-04-04 17:07:25

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); 
    }); 
}); 
相關問題