jQuery每个#anchor都做点什么

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

需要知道如何定位每个#anchor链接以在悬停时更改图像。目前我一个接一个地定位,我是否需要在每个循环函数中包装它?

提前致谢。

var originalpath = $('#fulltraceswap img').attr('src');
var root = window.location.protocol + "//" + window.location.host + "/home/";
//1
$("#fulltracerow .edgtf-iwt-title a[href='#aftermarketimage']").hover(
function(){       

    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);

//2
$("#fulltracerow .edgtf-iwt-title a[href='#productlifecycle']").hover(
 function(){       

    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);

编辑

我通过使用a[href^='#']选择所有以#开头的链接找到了我想要的东西。 Backstory - 我正在使用一个名为visual composer的wordpress插件,在链接选项中它不允许添加数据属性......除非我对其进行硬编码。所以我想要一个快速的解决方法。谢谢

 $("#fulltracerow .edgtf-iwt-title a[href^='#']").hover(

 function(){       

    //we get our current filename and use it for the src
    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);
jquery each
1个回答
0
投票

不。您不需要使用循环,因为如果指定了右选择器,则它适用于所有匹配的元素。

只有您需要的是使用任何css类(而不是id)定义任何全局选择器,但我建议您使用html5数据属性,因为它比css类更灵活。

建议:1)添加数据 - *例如。 data-changeImage例如用于使用此悬停操作的所有链接。

<a href="#a" data-changeImage>Test1</a>

2)将[href ='#aftermarketimage']更改为全局选择器,例如data-changeImage等数据属性然后它可以工作。

$("#fulltracerow .edgtf-iwt-title a[data-changeImage]").hover(function() {
    $(this).css('color', 'red');
},
function() {
    $(this).css('color', 'green');
});

JSFIDDLE

© www.soinside.com 2019 - 2024. All rights reserved.