[英]jQuery .on click event handler for img
I am trying to call a function on clicking an image using jQuery. 我试图使用jQuery单击图像调用函数。
My html code is as follows: 我的HTML代码如下:
<div id="fixed-navbar">
<div class="nav-left">
<img id="back" src="back.png">
</div>
... (some other code)
</div>
to call a function on clicking of the above image i am writing script as: 单击上面的图像来调用函数我正在编写脚本:
$("#back").on('click', '.nav-left', function(e) {
e.preventDefault();
window.history.back();
});
why isn't this working? 为什么这不起作用?
PS: These div's are added dynamically PS:这些div是动态添加的
You're binding the event on .nav-left
instead of #back
itself. 你在
.nav-left
上绑定事件而不是#back
本身。
$("#back").on('click', function(e) {
e.preventDefault();
window.history.back();
});
If your image is dynamically generated inside the div.nav-left
element, you just need to reverse the selectors. 如果您的图像是在
div.nav-left
元素内动态生成的, div.nav-left
需要反转选择器。
$(".nav-left").on('click', '#back', function(e) {
e.preventDefault();
window.history.back();
});
If all your content is dynamic, you need to do it this way. 如果您的所有内容都是动态的,则需要这样做。
$("body").on('click', '#back', function(e) {
e.preventDefault();
window.history.back();
});
Instead of body
, you can specify the closest enclosing parent element that is not dynamically added to the page. 您可以指定未动态添加到页面的最近的封闭父元素,而不是
body
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.