简体   繁体   English

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

[英]ajax response includes image, onClick event on image not working jQuery

im getting really crazy about this, i cant make a simple click() event in jQuery. 我对此感到非常疯狂,我无法在jQuery中创建一个简单的click()事件。 i really need your help on this. 我真的需要你的帮助。

i have ajax that will send data to a PHP file and the result will echo back as (response) 我有一个将数据发送到PHP文件的ajax,结果将作为(response)回显

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

included in the response, is this <img src="next.png" id="next" alt="" /> 包含在响应中的是<img src="next.png" id="next" alt="" />

i simply want the next image to be clickable and display some kind of alert. 我只是希望next图片可点击并显示某种警报。

below are my different variations on the code. 以下是我在代码上的不同变化。 but i still cant make the button work! 但我仍然无法使按钮正常工作!

//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");
    });
});

Use .on() 使用.on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation . 由于元素是动态添加的,因此无法将事件直接绑定到它们。因此,必须使用事件委托

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

or better 或更好

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

Syntax 句法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM