我有以下标记:
<div class="row">
<img src="image.png" class="download-image regular-image" />
<div class="options">
<p>download</p>
</div>
<img src="image.png" class="download-image regular-image" />
<div class="options">
<p>download</p>
</div>
以下代码来操作它(它改变了图像,基本上它是一个活跃的状态实现):
$(".download-image").click(function (event) {
event.stopPropagation();
$(this).next().toggle();
$('.download-image').removeClass('current').attr('src', 'image.png');
$(this).addClass("current").attr('src', 'image2.png');
$(document).delegate('.current','mouseover',function() {
$(this).attr("src", "image2.png");
});
$(document).delegate('.current','mouseout',function() {
$(this).attr("src", "image.png");
});
});
此代码运行良好,但我在单击元素时删除.current
类时遇到问题。通过点击页面的任何位置实现它,如下所示:
$("html").click(function() {
$(".options").hide();
$(".download-image").removeClass('current').attr("src", "image.png");
$(".download-image").hover(function() {
$(this).attr("src", "image2.png");
}, function() {
$(this).attr("src", "image.png");
});
});
这个块完全符合我的要求,但我也想为活动图像提供相同的行为。我尝试了什么:
1.将.current
添加到html
点击事件
2.为.current
类创建相同的函数
3.使用.on('click', '.current', function()
4.就这样:
$('.current').click(function() {
$(this).removeClass('current');
}
上面没有任何内容对我有用。哪里错了?任何帮助将不胜感激。
答案 0 :(得分:2)
侦听器的回调函数中的this关键字附加了事件对象。你想要HTML元素。您可以通过注销回调内部的值并查看对象来查看此操作。试试这个来获取HTML元素:
$('.current').on('click', function(e) {
$(e.target).removeClass('current');
}
记下我给回调的论点。我相信this.target可能实际上是同一个对象但我在移动atm所以无法验证。但是,您可以通过console.log(this)注销值;声明
答案 1 :(得分:0)
解决方案是如此明显,以至于我感到惭愧在发布我的问题之前我没有尝试过。我使用了.toggleClass()
方法,现在我的click()
事件看起来像这样:
$(".download-image").click(function (event) {
event.stopPropagation();
$(this).next().toggle();
$('.download-image').removeClass('current').attr('src', 'image.png');
$(this).toggleClass("current").attr('src', 'image2.png');
$(document).delegate('.current','mouseover',function() {
$(this).attr("src", "image2.png");
});
$(document).delegate('.current','mouseout',function() {
$(this).attr("src", "image2.png");
});
});
请注意,我使用的是旧版jQuery,如果您使用v3+
,则应将.delegate()
方法替换为.on()
,并在评论中提及。