使用jQuery .click函数单击监视图像上的单击

问题描述 投票:1回答:2

我正在为一个俱乐部使用Bootstrap,Node.js和jQuery创建一个网站。我正在尝试编写一段Javascript代码,当一个图像(或者最好是它所在的div)被点击时,另一个javascript函数我必须更改pdf显示才会运行。我的问题是无法捕捉到图像上的点击。

我的图像代码:

<div id="2005d" style="cursor: pointer">
    <img id="2005p" style="max-width: 100%" src="/magazines/2005_cover.jpg">
    <h5 id="2005t" style="text-align: center; color: black">2005</h5>
</div>

我想用jQuery来点击这个图像:

$("document").ready(function() {
    $("#2005d").click(function(){
        alert("Clicked");
    });
});

我该怎么做才能让jQuery捕获图像上的click事件?

javascript jquery html
2个回答
4
投票

使用JQuery Event Delegation在父元素上设置处理程序,但测试是否该事件源自图像并使用JQuery .on()方法而不是QQuery推荐的.click()

$("document").ready(function() {
    $("#2005d").on("click", "img" ,function(){
        alert("Clicked");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="2005d" style="cursor: pointer">
    <img id="2005p" style="max-width: 100%" src="https://image.spreadshirtmedia.com/image-server/v1/mp/designs/12386804,width=178,height=178/winking-smiley-face.png">
    <h5 id="2005t" style="text-align: center; color: black">2005</h5>
</div>

0
投票

你的代码是正确的,但你必须为图像写点击事件,试试这个工作

$("document").ready(function() {
 $("#2005p").click(function(){
    alert("Clicked");
 });
});
© www.soinside.com 2019 - 2024. All rights reserved.