【问题标题】:jQuery: Check if button is clickedjQuery:检查按钮是否被点击
【发布时间】:2013-03-14 08:59:24
【问题描述】:

我在一个表单中有两个按钮,想检查哪个按钮被点击了。 单选按钮一切正常:

if($("input[@name='class']:checked").val() == 'A')

在简单的提交按钮上一切都会崩溃。

谢谢!

【问题讨论】:

  • 发布您已经尝试过的代码。

标签: javascript jquery html


【解决方案1】:
$('#submit1, #submit2').click(function () {
   if (this.id == 'submit1') {
      alert('Submit 1 clicked');
   }
   else if (this.id == 'submit2') {
      alert('Submit 2 clicked');
   }
});

【讨论】:

  • @Kautil Typo 在您的 else 条件下。 submit1 应该是 submit2
【解决方案2】:

你可以用这个:

$("#id").click(function()
{
   $(this).data('clicked', true);
});

现在通过 if 语句检查它:

if($("#id").data('clicked'))
{
   // code here 
}

更多信息您可以访问the jQuery website on the .data() function.

【讨论】:

    【解决方案3】:
    jQuery(':button').click(function () {
        if (this.id == 'button1') {
            alert('Button 1 was clicked');
        }
        else if (this.id == 'button2') {
            alert('Button 2 was clicked');
        }
    });
    

    编辑:- 这适用于所有按钮。

    【讨论】:

    • 我的尝试:if($("input[@name='submit']:clicked").val() == 'button') $("input[type='button'] ").click(function(){ alert("id: "+$(this).attr("id")+" 的按钮被点击了!"); });这有效但对我不​​利,我有更多按钮而不仅仅是一个,所以我需要区分它。我已经尝试了很多代码并且遇到了一些问题,因为无法将其放入 if 语句中,因为不确定什么是 return true 或 1 或什么都没有(尝试了一切)。我正在寻找单选按钮的最简单和类似的解决方案。
    【解决方案4】:
    $('input[type="button"]').click(function (e) {
        if (e.target) {
            alert(e.target.id + ' clicked');
        }
    });
    

    你应该稍微调整一下(例如,使用名称而不是 id 来提醒),但这样你就有了更通用的功能。

    【讨论】:

      【解决方案5】:
      $('#btn1, #btn2').click(function() {
          let clickedButton = $(this).attr('id');
          console.log(clickedButton);
      });
      

      【讨论】:

        【解决方案6】:

        尝试类似:

        var focusout = false;
        
        $("#Button1").click(function () {
            if (focusout == true) {
                focusout = false;
                return;
            }
            else {
                GetInfo();
            }
        });
        
        $("#Text1").focusout(function () {
            focusout = true;
            GetInfo();
        });
        

        【讨论】:

          猜你喜欢
          • 2021-03-08
          • 2013-05-09
          • 2013-07-26
          • 1970-01-01
          • 1970-01-01
          • 2014-12-28
          • 2020-05-23
          • 2014-05-19
          • 1970-01-01
          相关资源
          最近更新 更多