我有一个jQuery函数,在带有类.myshp_list_product_image的<div>的events mouseover和mouseout上,它更改了它们的src属性。
问题是,当我悬停其中一个,它也改变了其他。
我怎么才能让它只改变被盘旋的那个呢?
下面是函数的代码:
$(function() {
$('.myshp_list_product_image').mouseover(function() {
$('.myshp_list_product_image').each(function() {
var $this = $(this);
$this.attr('src', $this.attr('src').replace('1s', '2s'));
});
});
$('.myshp_list_product_image').mouseout(function() {
$('.myshp_list_product_image').each(function() {
var $this = $(this);
$this.attr('src', $this.attr('src').replace('2s', '1s'));
});
});
});发布于 2017-02-15 13:56:34
你不需要.each()在这里,把它处理掉。您只需要针对当前元素,即this。
$(function() {
$('.myshp_list_product_image').mouseover(function() {
var $this = $(this);
$this.attr('src', $this.attr('src').replace('1s', '2s'));
});
$('.myshp_list_product_image').mouseout(function() {
var $this = $(this);
$this.attr('src', $this.attr('src').replace('2s', '1s'));
});
});我建议您使用mouseenter和mouseleave事件,用于mouseover和mouseenter之间的区别的小演示
发布于 2017-02-15 13:59:17
只针对当前悬停/悬停的元素,而不是对具有相同类的所有元素进行迭代。
此外,您还可以使用.hover而不是mouseover和mouseout以及.attr()的回调函数来最小化代码:
$('.myshp_list_product_image').hover(
function() {
$(this).attr('src',function(i,oldattr){return oldattr.replace('1s', '2s')});
}, function() {
$(this).attr('src',function(i,oldattr){return oldattr.replace('2s', '1s')});
});发布于 2017-02-15 14:01:00
我将使用来自jQuery的jQuery()
$(function () {
$('.myshp_list_product_image').hover(function () { // mouse in
var $this = $(this);
$this.attr('src', $this.attr('src').replace('1s', '2s'));
}, function () { // mouse out
var $this = $(this);
$this.attr('src', $this.attr('src').replace('2s', '1s'));
});
});https://stackoverflow.com/questions/42251316
复制相似问题