0

当页面呈现时存在类时,以下代码有效:

$().ready(function () {

    $(".productzoom").on('hover click', function () {//also add this function to click
        $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
        $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
    });
});

但是,后来我动态插入内容,当我将鼠标悬停或单击 .productzoom 类时,上面的代码似乎不再起作用。我认为通过使用 .on jQuery 会将钩子也附加到新插入的元素上,但它没有......为什么?

4

2 回答 2

3

根据 jquery .on()文档,事件处理程序仅绑定到当前选定的元素;当您的代码调用.on(). 如果将新 HTML 注入页面,请在将新 HTML 放入页面后选择元素并附加事件处理程序。或者,使用委托事件附加事件处理程序,因此您需要执行以下操作:

$(document).on('hover click', '.productzoom', function () {//also add this function to click
     $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
     $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
});
于 2013-11-08T02:39:09.750 回答
1

由于您正在处理动态元素,因此您需要使用事件委托......因为.on()的语法略有不同

事件委托语法是$(<staticelement>).on(event, <dynamic target selector>, handler)

$(document).on('hover click', ".productzoom", function () { //also add this function to click
    $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
    $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
});

您的代码可以更改为更好的格式,例如

$(document).on('hover click', ".productzoom", function () { //also add this function to click
    var position = $(this).position();
    $(this).closest(".product1").find(".image span").css({
        'top': position.top - 200,
        'left': position.left + 20
    });
});
于 2013-11-08T02:38:20.057 回答