Detect click on an image

孤街醉人 提交于 2019-12-07 01:25:04

问题


I am trying to load images dynamiaclly and displaying them as shown below

     var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
              uploader.bind('FileUploaded', function (up, file, res) {
              $('#<%=thumbs.ClientId%>').append("<div id=" + file.id + ">
              <a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/>
              <img src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='70' height='55' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
    });

This is my markup:

  <div id="thumbs" class="imgContain" runat="server">
  </div>

If I do this way on the div it gives me an alert but not on the image but on the div:

  $('.imgContain').click(function () {
    alert('You Clicked Me');
  });

And I have tried using this way but it dosent give me any alert not even on the div also.

 $('.imgContain a').click(function () {
        alert('You Clicked Me');
 });

So how do I do this?


回答1:


you should use the on method

 $('.imgContain').on("click","a,img", function (e) {
      e.preventDefault();
      alert('You Clicked Me');
 });



回答2:


It's a little hard to know exactly what your DOM looks like, but I guess you add the images to the div with class .imgContain. If you want to add a click event to those images you could do something like this:

$('.imgContain').on("click", "img", function () {
    alert('You Clicked Me');
});

As I believe you are adding the images dynamically, you should use the .on() method to bind the click event, instead of using .click().

Note If you for some reason are using a previous version of jQuery, you could change the .on() to use .live() instead.




回答3:


For the anchors <a>s that you appended, youwill need to use .live() in order to attach to it the click event like:

 $('.imgContain a').live("click", function (event) {
      event.preventDefault();
      alert('You Clicked Me');
 });



回答4:


Learn function live in jQuery. and use that in your code..

jQuery version 1.4.1 and above.

since the elements are placed on the html dynamically after your page is loaded. Click function is not binded.



来源:https://stackoverflow.com/questions/9148409/detect-click-on-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!