ajax 响应包括 image,onClick 事件对图像不起作用 jQuery

ajax response includes image, onClick event on image not working jQuery

本文关键字:图像 不起作用 jQuery 事件 onClick 响应 包括 image ajax      更新时间:2023-09-26
我对此感到

非常疯狂,我无法在jQuery中制作一个简单的click()事件。 我真的需要你的帮助。

我有 ajax 将数据发送到 PHP 文件,结果将回显为(response)

$.post("get.php?data="+ data, {
  }, function(response){
  $('#load').html(response);

包含在响应中,是<img src="next.png" id="next" alt="" />

我只是希望next图像可点击并显示某种警报。

以下是我对代码的不同变体。 但我仍然无法使按钮工作!

//test 1
$(document).ready(function () {
    $('#next').livequery("click", function () {
        alert("test");
    });
});
//test 2
$(document).ready(function () {
    $('#next').on("click", function () {
        alert("test");
    });
});
//test 3
$(document).ready(function () {
    $('img#next').on("click", function () {
        alert("test");
    });
});
//test 4
$(document).ready(function () {
    $('#next').on("click", "img", function () {
        alert("test");
    });
});
//test 5
$(document).ready(function () {
    $('#next').on("click", "img", function (e) {
        e.preventDefault();
        alert("test");
    });
});

使用 .on()

由于元素是动态添加的,因此您无法将事件直接绑定到它们。因此,您必须使用事件委派。

$(document).ready(function () {
    $(document).on("click", "#next", function (e) {
        e.preventDefault();
        alert("test");
    });
});

或更好

$(document).ready(function () {
    $("#load").on("click", "#next", function (e) {
        e.preventDefault();
        alert("test");
    });
});

语法

$( elements ).on( events, selector, data, handler );