JQuery $ ("img"). Click (function () selector not working

For some reason, when I click on an image using this jQuery code, the warning screen does not appear.

HTML:

<div id="example1"> <div> <div> <div class="user"> <img class="Image" src="images/image.jpg"> </div> </div> </div> </div> 

JavaScript:

 $(document).ready(function(){ $("img").click(function(){ alert("it works!"); }); }); 

I can’t understand why this is not working. I have included the jquery library and the <script> is under the div

+11
source share
5 answers

img is not in the DOM when your event handler is registered. you can use $('body').on('click','img',function(){alert('it works');})

+26
source
  $(document).ready(function(){ $(".Image").click(function(){ alert("it works!"); }); }); 

If you want your code to work without change, just put .Image not img the class name does not assign a name

+3
source

Instead of running your code in document.ready (), you should use the window.load () function instead.

 $(window).load(function() { $("img").click(function(){ alert("it works!"); }); }); 
  • document.ready () is a jQuery event, it is executed when the DOM is ready, for example. all items must be found / used, but not necessarily all content.
  • window.load () is triggered later (or at the same time in the worst / bad cases) when the images are loaded, so if you are using the image dimensions for example, you often want to use this instead.
+2
source

For some reason, when I click on the image with this jquery code, the warning screen does not appear.

I use the jquery plugin to get Twitter images from people who used #Image, this works great and exposes html that looks like this.

If I try the selector with the body instead of the image, a warning will appear, but I can not get it to work with the image selector, why doesn’t it respond?

i included jquery as follows:

 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

im 100% sure html is checked correctly at least 10 times.

the only error the console gives is: "Attr.nodeValue" is deprecated. Use "value" instead. but I don’t think this should stop the jquery above working on the body when I tried the script below the div, it didn’t work either.

HTML:

 <div id="example1"> <div> <div> <div class="user"> <img class="Image" src="images/image.jpg"> </div> </div> </div> </div> 

JavaScript:

 $(document).ready(function(){ $("img").click(function(){ alert("it works!"); }); }); 
0
source

Try this, this works with images coming from ajax request too.

 $(document).on('click','img',function(){ alert("Click event works!"); }); 
0
source

Source: https://habr.com/ru/post/1203610/


All Articles