我是 jQuery 新手。我必须对段落中的某些链接执行相同的功能,从而影响某些图像。
所有链接都有一个 id 和 img。
这是示例代码:
$("#link1").hover(function () {
$("#img1").removeClass("hover");
}, function () {
$("#img1").addClass("hover");
});
$("#link2").hover(function () {
$("#img2").removeClass("hover");
}, function () {
$("#img2").addClass("hover");
});
等等。 您知道是否有更好的方法来避免每次为所有项目重写相同的代码?
最佳答案
使用starts with
选择器。查找 DOM 中以 ID = 'link' 开头的所有元素,并定位相应的 <img>
使用 replace()
的元素方法。
$(document).find("[id^='link']").hover(function ()
{
$("#" + this.id.replace("link","img")).removeClass("hover");
}, function () {
$("#" + this.id.replace("link","img")).addClass("hover");
});
关于javascript - jQuery合并不同id的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510932/