在onclick事件后调用按钮的id到javascript文件

时间:2017-07-14 23:08:17

标签: javascript jquery html

我使用这个通用代码创建了几个按钮:

   <button class="button" id = "b1" value="0" onclick="checker()"></button>

我目前正在撰写javascript&#39; checker()&#39;检查&#39; id&#39;按钮的外部值匹配。要做到这一点,我需要&#39; id&#39;单击相应按钮后发送到我的脚本的按钮。然后,我会设置&#39; id&#39;变量为值。我怎样才能做到这一点?我可以用一个我知道id的按钮,但我希​​望我的代码是通用的。我愿意使用jQuery。

2 个答案:

答案 0 :(得分:1)

首先让我们创建一个接受id作为参数的javascript方法:

var checker = function(id)
{
  //we will do something here later, lets understand this now
}
  

我需要将按钮的'id'发送到我的脚本   点击相应的按钮。

因此,如果要获取事件处理程序绑定的元素的ID,可以使用this.idthis引用元素)轻松完成此操作,如下所示:

<button class="button" id = "b1" value="0" onclick="checker(this.id)"></button>
  

然后,我将'id'变量设置为一个值。我怎样才能做到这一点?一世   我愿意使用jQuery。

您可以通过以下代码执行此操作,基本上我们会获得所点击按钮的id,在您的方法内部,您可以使用id执行任何操作。通过阅读您的评论,我看到您只需将id的值分配给某个xyz变量:

var checker = function(id)
{
   var xyz = id; // now your xyz has a value of clicked button id
}

答案 1 :(得分:0)

由于您愿意使用jQuery 希望保持代码的通用性,因此可以通过更少的输入来实现您想要的更简单的方法。

您的按钮

<button class="button" id = "b1" value="0"></button>

您的JavaScript

//be sure to include jQuery
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text\javascript">
    //you must call this for jQuery to load/function
    $(function(){
         //anything that has a class of "button", attach this handler
         //this handles any "click" of a button with class "button"
         $(".button").on("click", function(){
               //alert the attribute of id for whatever element (this) was 
               //clicked
               alert($(this).attr("id"));
         });
    });
</script>

以下是一个工作示例代码段

&#13;
&#13;
$(function(){
    $(".button").on("click", function(){
         var btnId = $(this).attr("id");
         alert(btnId);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="button" id="b1" value="B1">B1</button>
<button class="button" id="b2" value="B2">B2</button>
&#13;
&#13;
&#13;