如何为不同 类 创建一个 jquery 单个 mouseenter() 事件

How to create a jquery single mouseenter() events for different classes

您好,我正在尝试将一系列 mouseenter 事件归为一个,但我对 javascript 还是个新手,我真的很困惑,我想创建一个事件来包含所有这些事件。”.slider-button- 1" 类 现在数到 5。

$("#slider-s-pic .slider-button-1").mouseenter(function () {
    $(".slider-inner ul").animate({ marginLeft: "-" + (liWidth * 0) + "px" });
});

我的整个项目都在 codepen 中 -> codepen.io/FreeMaNn/pen/ZagweX

您的选择器将以逗号 (,) 分隔。试一试

$("#slider-s-pic , .slider-button-1").mouseenter(function () {
    $(".slider-inner ul").animate({ marginLeft: "-" + (liWidth * 0) + "px" });
});

你可以使用像

这样的东西
$("#slider-s-pic a[class^='slider-button-']").mouseenter(function () {
    var GetIndex = $(this).closest('li').index();
    $(".slider-inner ul").animate({ 
       marginLeft: "-" + (liWidth * GetIndex) + "px" 
     });
});

a[class^='slider-button-'] - select 所有 类 以 slider-button-

开头

^ - 开头为 * - 包含 $ - 以

结尾

var GetIndex = $(this).closest('li').index(); - 获取 li 索引 .. 不要使用 $(this).index() 它每次都会 return 0 .. 所以你需要使用 .closest('li')

试试吧。它会起作用。

$(document).on( 'mouseenter', '#slider-s-pic , .slider-button-1',(function () {
    $(".slider-inner ul").animate({ marginLeft: "-" + (liWidth * 0) + "px" });
});