将事件侦听器附加到jQuery中动态生成的图像

Attaching event listener to dynamically generated image in jQuery?

本文关键字:动态 图像 jQuery 侦听器 事件      更新时间:2023-09-26

我使用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")为空,因此事件处理程序没有附加到任何内容。