简体   繁体   English

您如何使html中的多个按钮指向同一个JS函数

[英]How would you make multiple buttons in html point to the same JS function

I want 'div#Welcome a' and 'div#Familiarize a' to point to this JS code: 我希望“ div#Welcome a”和“ div#Familiarize a”指向此JS代码:

    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;

right now i have this: 现在我有这个:

$('div#Welcome a').click(function(e){

and this: 和这个:

$('div#Familiarize a').click(function(e){

for the click to go to the specified code. 单击以转到指定的代码。 I was wondering if there was a way that anything that i wanted to be linked with this could could be without having to make a new function every time. 我想知道是否有一种方法可以使我想要与此关联的任何东西都不必每次都进行新功能。 Is there an ID for certain tags that i can put on? 我可以贴上某些标签是否有ID? Thank you in advance. 先感谢您。

Make your code block into a named function and pass that to your event handlers: 使您的代码块成为一个命名函数,并将其传递给事件处理程序:

function myEventHandler(e) {
    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;
}

$('div#Familiarize a').click(myEventHandler);
$('div#Welcome a').click(myEventHandler);

Or as @mark.hch and @Huangism have pointed out, you can also use comma-separated selectors: 或就像@ mark.hch和@Huangism指出的那样,您也可以使用逗号分隔的选择器:

$('div#Familiarize a, div#Welcome a').click(myEventHandler);

You can use multiple selectors together by separating them with comma. 您可以使用逗号将多个选择器一起使用。

$('div#Familiarize a, div#Welcome a').click(function(e) {
    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;
});

Although to simplify things, I suggest giving all the relevant DIV sa common class, and using that in the selector: $('div.tab a').click(...) 尽管为了简化起见,我建议给所有相关的DIV一个通用类,并在选择器中使用它: $('div.tab a').click(...)

You could also give each div the same class and attach the handler to that. 您还可以给每个div相同的类,并将处理程序附加到该类。

<div class="thisclass">

$('.thisclass').click(function (e) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM