如何在jQuery中绑定同一事件上的多个id

How to bind multiple ids on same event in jQuery?

本文关键字:事件 id jQuery 绑定      更新时间:2023-09-26

这是我的HTML代码:

<a style='cursor:pointer'   id='anchor1' onmouseover=fnover(this)>
<a style='cursor:pointer'   id='anchor2' onmouseover=fnover(this)>
<a style='cursor:pointer'   id='anchor3'  onmouseover=fnover(this)>

这是我的JavaScript代码:

fnover(obj){
     $('.dropdown').fadeIn();
}

我的要求是,我有多个id,但我想使用jQuery动态绑定id。每当您将鼠标悬停在锚点标记上时,特定的锚点标记都将是fadeInfadeOut

有什么建议吗?

$('#id1,#id2,#id3').on('mouseenter',function(){
   //do stuff on mouse over
});
$('#id1,#id2,#id3').on('mouseleave',function(){
   //do stuff on mouse out
});

当然,如果你只是给你的项目一个类,而不是一个单独的id,这会更容易,因为它们似乎做着同样的事情。。。

$('.myclass').on('mouseleave',function(){
   //do stuff on mouse out
});

你的意思是这个吗

<a style='cursor:pointer' id='anchor1' />
<a style='cursor:pointer' id='anchor2' />
<a style='cursor:pointer' id='anchor3' />

然后将相同的功能绑定到所有三个锚

$('#anchor1, #anchor2, #anchor3').hover(function(){ //Select all three
    $('.dropdown').fadeIn();                        //On mouse over
}, function(){
    $('.dropdown').fadeOut();                       //on mouse out
});

尽管编写此代码时最好将您希望将此功能附加到aFade之类的类的所有锚点标记都提供给它们,然后使用进行选择

$('.aFade').hover(function.........

您可以传递多个选择器,用类似的逗号分隔

$( "#anchor1, #anchor2, #anchor3" ).mouseover(function() {
  $('.dropdown').fadeIn();
});

试试这个:

 onmouseover=fnover($(this).attr("id"))

为什么不为每个HTML元素添加一个类,并使用getElementByClass()函数来选择要在上使用fadeIn()和fadeOut()的元素。

如果锚标记id的有一些通用名称,您可以执行类似的操作

$(function(){
    $("a[id*=anchor]").mouseover(function(){
       //do your stuff here 
    });
});

上面的脚本指出,如果任何锚标记的id以anchor开头,那么事件将被连接起来。您甚至不必指定锚点标记的所有id。

如果你有一些常见的.classname作为你的锚标签,那也更好。这样,只有特定的类名才会连接事件。

这是小提琴

希望它能帮助