jQuery点击功能的多个目标ID

jQuery multiple target IDs for click function

这可能有点多余,但我想知道是否有一种方法可以通过缩短代码来避免重复来改进代码。

$('a[href*="#about"]').click(function() 

我要定位 #about #products #process #gallery #contact

我想避免:

$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function() 

给他们一个 class 并瞄准:

$(".the-class").click(function() {
    // ...
});

如果你不能那样做,那么你想要避免(但正确完成)的就是你需要做的:

$("[href=#about], [href=#products], [href=#process], [href=#gallery], [href=#contact]").click(function() {
    // ...
});

或者,您可以在页面上设置一个单击处理程序,并根据单击的元素进行委托。

var handledHrefs = ['#about', '#products', '#process', '#gallery', '#contact'];
$('body').on('click', 'a[href^=#]', function (e) {
  if (handledHrefs.includes(e.target.attr('href'))) {
    // ...
  }
});

这实际上比附加单个事件处理程序具有更好的性能,这已经足够令人惊讶了。