2013-02-03 50 views
0

我使用jquery動態地將圖像添加到我的頁面。基本上,我在頁面上創建圖像的「pixel-y/lo-res」版本,並在原稿的頂部添加頁面加載。然後,一個典型的「淡出懸停」的東西應該在鼠標懸停時淡出它們,顯示出orignals ......就好像「up-rezing」..如果這是有道理的。將事件偵聽器附加到jQuery中的動態生成的圖像?

所以我有圖像進來..但不知何故,懸停監聽沒有附加。起初,我嘗試懸停,現在我點擊只是因爲它更容易排除故障。沒有。

.on()函數應該附加自己,甚至動態添加項目,對吧?出了什麼問題?我沒有收到任何錯誤。這只是不工作。

$.ajax({ 
     type:"POST", 
     url:"js/pixelsandwich/pixelsandwich.php", 
     data:{src:src}, 
     success:function(response){ // if there is already a "lo-rez" image, I get that URL.. if there isn't, one is created and I return that URL 
      newImg = $("<img class='crunched'>"); // create the new <img> 
      newImg.attr('src', response); // assign the source 
      frame = $that.parent(); // grab the containing frame 
      frame.append(newImg); // add the new image. css:position:absolute and z-index take care of the rest 
     } 
    }); 

$(".crunched").on("click", function(){ // << this just isn't attaching at all 
    alert("hello"); 
    $(this).fadeTo('slow',0.5); 
}); 

有人幫忙嗎?

回答

2

.on()函數應該附加自己,甚至動態地添加 項目,對吧?

不可以,動態創建的元素必須使用.on()綁定到代碼運行時已存在的元素。最糟糕的情況通常是body元素,但是您可以在DOM中選擇的元素越接近越好。

假設.crunched是班級的動態添加元素,嘗試:

$("body").on("click", ".crunched", function(){ // << this just isn't attaching at all 
    alert("hello"); 
    $(this).fadeTo('slow',0.5); 
}); 

每jQuery的文檔:

事件處理程序只能綁定到當前選擇的元素;在代碼調用.on()時,頁面上必須存在 。 要確保元素存在並且可以選擇,請在頁面上的HTML標記中的 HTML標記中對元素執行文檔就緒處理程序內的事件 綁定。如果新頁面被注入頁面, 選擇元素並附加事件處理程序,當新的HTML被放置到頁面中時,頁面中的內容爲 。

0

on方法應當用於委託的事件處理到現存祖先動態添加元素的。例如:

$(document).on("click", ".crunched", function(){ // << this just isn't attaching at all 
    alert("hello"); 
    $(this).fadeTo('slow',0.5); 
}); 

收集$(".crunched")是空的,當你運行你的代碼,因此事件處理程序沒有被連接到任何東西。

相關問題