Jquery $("img").click(function() 选择器不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26098866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:13:42  来源:igfitidea点击:

Jquery $("img").click(function() selector not working

jqueryhtmlselector

提问by Stefan

For some reason when I click on an image with this JQuery code the alert screen doesn't show up.

出于某种原因,当我单击带有此 JQuery 代码的图像时,警报屏幕没有显示。

HTML:

HTML:

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

Javascript:

Javascript:

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

I cant figure out why this isn't working I included the jquery library and the <script>tag is under the div

我不知道为什么这不起作用我包含了 jquery 库并且<script>标签在 div 下

回答by electrophanteau

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

注册事件处理程序时,img 不在 DOM 中。您可以使用$('body').on('click','img',function(){alert('it works');})

回答by Biosopher

Rather than run your code in document.ready(), you should use window.load() function instead.

与其在 document.ready() 中运行代码,不如使用 window.load() 函数。

$(window).load(function() {
    $("img").click(function(){
        alert("it works!");
     });
});
  • document.ready() is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.
  • window.load() fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.
  • document.ready() 是一个 jQuery 事件,它在 DOM 准备好时运行,例如所有元素都可以找到/使用,但不一定是所有内容。
  • window.load() 在加载图像等时稍后触发(或在最坏/失败的情况下同时触发),因此,例如,如果您使用图像尺寸,您通常想改用它。

回答by Mostafa Anssary

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

IF you want your code to work with out change just put .Image not img the class name not attribue name

如果您希望您的代码无需更改即可工作,只需放置 .Image not img 类名而不是属性名称

回答by csandreas1

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

试试这个,它也适用于来自 ajax 请求的图像。

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