【问题标题】:Access click event of two buttons using jquery使用jquery访问两个按钮的点击事件
【发布时间】:2016-11-09 05:17:39
【问题描述】:

我有 2 个名为 Button1 和 Button2 的 html 按钮。

两个按钮使用 jquery 执行相同的操作。

现在我在两个按钮的单击事件中编写了相同的 jquery。如下所示

 $('#Button1').click(function () {
 xyz //some jquery
  })



 $('#Button2').click(function () {
 xyz //some jquery
  })

两个 jquery 是相同的。我可以抓住两者的点击事件吗 单个功能中的按钮?

【问题讨论】:

标签: jquery


【解决方案1】:

您可以使用multiple selector

$('#Button1, #Button2').click(function() {
    // You can use `this` to refer to the source element, for instance:
    $(this).css("color", "red");
});

【讨论】:

  • @fedric。只是想澄清一些问题。如果我这样做了,有没有办法了解哪个按钮导致事件????
  • @Null 指针,是的,你可以在事件处理程序中使用this 来引用源元素。
【解决方案2】:

声明一个函数并将其用作参数。例如:

function handleClick() {
    // Do something..
}

$('#Button1').click(handleClick);
$('#Button2').click(handleClick);

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    我会在按钮上使用一个类:

    $('.className').click(function() {
        var item = $(this); // item that triggered the event
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2018-09-08
      • 2014-02-21
      • 1970-01-01
      相关资源
      最近更新 更多