簡體   English   中英

在jQuery中附加事件監聽器到動態生成的圖像?

[英]Attaching event listener to dynamically generated image in jQuery?

我用jquery動態地將圖像添加到我的頁面。 基本上我在頁面上創建圖像的“pixel-y / lo-res”版本,並在頁面加載超過原始頁面。 然后一個典型的“懸停淡出”的東西應該在鼠標懸停時淡出它們,顯示出這些信號......仿佛“向上 - 放逐”......如果這是有道理的。

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

.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);
});

有誰幫忙?

.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放入頁面后選擇元素並附加事件處理程序。

應該使用on方法將事件處理委托給動態添加元素的現存祖先 例如:

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

運行代碼時,集合$(".crunched")為空,因此事件處理程序不會附加到任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM