【问题标题】:onClick to get the ID of the clicked buttononClick 获取被点击按钮的ID
【发布时间】:2011-06-17 01:16:52
【问题描述】:

如何找到被点击的按钮的id?

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

function reply_click()
{
}

【问题讨论】:

  • @Robin van Baalen:ID 不应该按照惯例是数字,但可以。

标签: javascript html


【解决方案1】:

您需要将 ID 作为函数参数发送。这样做:

<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
    
<script type="text/javascript">
  function reply_click(clicked_id)
  {
      alert(clicked_id);
  }
</script>

这会将 ID this.id 作为clicked_id 发送,您可以在函数中使用它。 See it in action here.

【讨论】:

  • 我只想指出,对于任何使用 JQuery 的 event.target.id 获得空引用异常的人(对我来说,Firefox 和 IE 都在抛出它),这是一个适用于所有三个主要领域的出色解决方案浏览器。
  • 兄弟,你是互联网上唯一一个能够为我解释这种工作方式的人。在函数名称中使用变量而不是在实际函数脚本中使用另一个变量对我来说绝对没有意义!你用一句话向我解释了我们放在函数括号()中的变量和我们在函数声明中使用的变量是一样的,只是在 AS 上传递!这太棒了!感谢主赐予我的智慧
  • 你真的不希望你的 html 中有任何代码,比如
  • if (this.id == "1") { console.log("btn 1 is Activated"); }
  • 有人告诉我,为什么有些人不想要内联 Javascript 代码?
【解决方案2】:

一般来说,如果您将代码和标记分开,事情会更容易保持井井有条。定义所有元素,然后在 JavaScript 部分中,定义应对这些元素执行的各种操作。

当一个事件处理程序被调用时,它是在被点击的元素的上下文中调用的。因此,标识符 this 将引用您单击的 DOM 元素。然后,您可以通过该标识符访问元素的属性。

例如:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

<script type="text/javascript">
var reply_click = function()
{
    alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>

【讨论】:

  • 如果按钮在中继器中并因此动态生成,所以你不知道你会有多少按钮?
  • 有很多方法可以解决这个问题。例如,动态生成 javascript。或者,将相同的类添加到所有按钮,然后遍历具有该类名称的所有按钮并以这种方式附加处理程序。
  • @JasonLeBrun 我不知道我要点击的元素的 id 是什么。这就是我要找的。一段代码绘制了一个 SVG 元素,当我点击它时,我需要知道它的“id”属性。是否以及如何使用此代码?
  • 我知道这是一个旧线程,但在我的现代浏览器 (FireFox 78) 上,您的 this 实现没有按预期工作。我的函数是由输入文本框的 onkeyup 事件触发的,但 this 使用的是 window 节点。相反,我不得不使用 event.srcElement
【解决方案3】:

使用纯 JAVASCRIPT: 我知道已经晚了,但它可能对未来的人有帮助:

在 HTML 部分:

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

在 Javascipt 控制器中:

function reply_click()
{
    alert(event.srcElement.id);
}

这样我们在调用javascript函数的时候就不用绑定Element的'id'了。

【讨论】:

  • 我喜欢这个动态功能的想法。我正在使用 PHP/MySQL 和 JS 向动态数据库添加函数;这对于向特定动态类添加特定功能非常有效。谢谢!
  • @codeling 可以分享一下浏览器和环境的详细信息吗?
  • @Prateek Firefox,最新。我只需要源代码,所以我现在通过在onClick 中传递this 作为参数来解决它(实际上,不使用onClick 而是使用onChange,这可能是问题吗?)。我也检查了一下,似乎有很多关于这个event 变量的混淆 - 它是一个“隐式”参数还是必须明确声明为参数(即function reply_click(event),我在某些地方也见过)?是否仅在通过addEventListener...分配事件侦听器时可用?我玩过,但无法让它工作。
  • 仅供参考:全局事件对象在 chrome 中可用,而不是 firefox。
  • 自 2021 年起, event.srcElement 已弃用。
【解决方案4】:

(我认为id 属性需要以字母开头。可能是错误的。)

您可以进行事件委托...

<div onClick="reply_click()">
    <button id="1"></button>
    <button id="2"></button>
    <button id="3"></button>
</div>

function reply_click(e) {
    e = e || window.event;
    e = e.target || e.srcElement;
    if (e.nodeName === 'BUTTON') {
        alert(e.id);
    }
}

...但这需要您对古怪的事件模型感到相对熟悉。

【讨论】:

  • 这行不通。您已在 onclick 属性中指定了调用 reply_click 且不带参数的代码。因此,不会将任何事件参数传递给函数。
  • 并且“id”属性的值可以是任意字符串。它不必以字母开头。
  • @Jason 实际上,在所有优秀的现代浏览器中,e 参数是自动生成的。如果不是,那么我们必须处理 IE6-8,它通过 window.event 提供有用的对象。
  • @sdleihssirhc 其实你这个狂妄自大的某某that all changes with HTML5
  • 感谢这对我有用,即使我的 id 是动态的并且似乎没有其他答案有效。非常感谢。
【解决方案5】:
<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>

function reply_click(obj)
{
var id = obj.id;
}

【讨论】:

    【解决方案6】:
    <button id="1" class="clickMe"></button>
    <button id="2" class="clickMe"></button>
    <button id="3" class="clickMe"></button>
    
    <script>
    $('.clickMe').click(function(){
        alert(this.id);
    });
    </script>
    

    【讨论】:

      【解决方案7】:

      如何在没有内联 JavaScript 或外部库的情况下做到这一点

      一般建议避免使用内联 JavaScript,但很少有如何做到这一点的示例。
      这是我将事件附加到按钮的方式。
      与简单的onClick 属性相比,推荐的方法要多长时间,我并不完全满意。

      现代浏览器

      • 在文档加载完成之前工作。
      • 非常高效。
      • 将 JS 与 HTML 分开。
      • JS 在&lt;head&gt;

      const OnEvent = (doc) => {
          return {
              on: (type, selector, callback) => {
                  doc.addEventListener(type, (event)=>{
                      if(!event.target.matches(selector)) return;
                      callback.call(event.target, event);
                  }, false);
              }
          }
      };
      
      
      OnEvent(document).on('click', '.btn', function (e) {
          let div = document.createElement("div");
          div.innerHTML = "click " + e.target.id + "!";
          document.body.appendChild(div);
      });
      <button id="b1" class="btn">Button 1</button>
      <button id="b2" class="btn">Button 2</button>
      <button id="b3">Do nothing</button>

      仅限 2014 年浏览器

      <button class="btn" id="b1">Button</button>
      <script>
      let OnEvent = (doc) => {
          return {
              on: (event, className, callback) => {
                  doc.addEventListener('click', (event)=>{
                      if(!event.target.classList.contains(className)) return;
                      callback.call(event.target, event);
                  }, false);
              }
          }
      };
      
      
      OnEvent(document).on('click', 'btn', function (e) {
          window.console.log(this.id, e);
      });
      
      </script>
      

      仅限 2013 年浏览器

      <!DOCTYPE html>
      <html>
      <head>
      <script>
      (function(doc){
          var hasClass = function(el,className) {
              return el.classList.contains(className);
          }
          doc.addEventListener('click', function(e){
            if(hasClass(e.target, 'click-me')){
                e.preventDefault();
                doSomething.call(e.target, e);
            }
          });
      })(document);
      
      function insertHTML(str){
        var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
        lastScript.insertAdjacentHTML("beforebegin", str);
      }
      
      function doSomething(event){
        console.log(this.id); // this will be the clicked element
      }
      </script>
      <!--... other head stuff ...-->
      </head>
      <body>
      
      <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
      <script>
      insertHTML('<button class="click-me" id="btn1">Button 1</button>');
      </script>
      
      <!--Use this when you don't care about broken buttons when javascript is disabled.-->
      <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
      <button class="click-me" id="btn2">Button 2</button>
      <input class="click-me" type="button" value="Button 3" id="btn3">
      
      <!--Use this when you want to lead the user somewhere when javascript is disabled-->
      <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
      
      </body>
      </html>
      

      跨浏览器

      <!DOCTYPE html>
      <html>
      <head>
      <script type="text/javascript">
      (function(doc){
          var cb_addEventListener = function(obj, evt, fnc) {
              // W3C model
              if (obj.addEventListener) {
                  obj.addEventListener(evt, fnc, false);
                  return true;
              } 
              // Microsoft model
              else if (obj.attachEvent) {
                  return obj.attachEvent('on' + evt, fnc);
              }
              // Browser don't support W3C or MSFT model, go on with traditional
              else {
                  evt = 'on'+evt;
                  if(typeof obj[evt] === 'function'){
                      // Object already has a function on traditional
                      // Let's wrap it with our own function inside another function
                      fnc = (function(f1,f2){
                          return function(){
                              f1.apply(this,arguments);
                              f2.apply(this,arguments);
                          }
                      })(obj[evt], fnc);
                  }
                  obj[evt] = fnc;
                  return true;
              }
              return false;
          };
          var hasClass = function(el,className) {
              return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
          }
      
          cb_addEventListener(doc, 'click', function(e){
            if(hasClass(e.target, 'click-me')){
                e.preventDefault ? e.preventDefault() : e.returnValue = false;
                doSomething.call(e.target, e);
            }
          });
      })(document);
      
      function insertHTML(str){
        var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
        lastScript.insertAdjacentHTML("beforebegin", str);
      }
      
      function doSomething(event){
        console.log(this.id); // this will be the clicked element
      }
      </script>
      <!--... other head stuff ...-->
      </head>
      <body>
      
      <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
      <script type="text/javascript">
      insertHTML('<button class="click-me" id="btn1">Button 1</button>');
      </script>
      
      <!--Use this when you don't care about broken buttons when javascript is disabled.-->
      <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
      <button class="click-me" id="btn2">Button 2</button>
      <input class="click-me" type="button" value="Button 3" id="btn3">
      
      <!--Use this when you want to lead the user somewhere when javascript is disabled-->
      <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
      
      </body>
      </html>
      

      jQuery 跨浏览器

      <!DOCTYPE html>
      <html>
      <head>
      <script type="text/javascript">
      (function($){
          $(document).on('click', '.click-me', function(e){
            doSomething.call(this, e);
          });
      })(jQuery);
      
      function insertHTML(str){
        var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
        lastScript.insertAdjacentHTML("beforebegin", str);
      }
      
      function doSomething(event){
        console.log(this.id); // this will be the clicked element
      }
      </script>
      <!--... other head stuff ...-->
      </head>
      <body>
      
      <!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
      <script type="text/javascript">
      insertHTML('<button class="click-me" id="btn1">Button 1</button>');
      </script>
      
      <!--Use this when you don't care about broken buttons when javascript is disabled.-->
      <!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
      <button class="click-me" id="btn2">Button 2</button>
      <input class="click-me" type="button" value="Button 3" id="btn3">
      
      <!--Use this when you want to lead the user somewhere when javascript is disabled-->
      <a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
      
      </body>
      </html>
      

      您可以在文档准备好之前运行它,单击按钮将起作用,因为我们将事件附加到文档。

      这是jsfiddle
      出于某种奇怪的原因,insertHTML 函数在其中不起作用,即使它在我所有的浏览器中都可以使用。

      如果您不介意 drawbacks,您可以随时将 insertHTML 替换为 document.write

      <script>
      document.write('<button class="click-me" id="btn1">Button 1</button>');
      </script>
      

      来源:

      【讨论】:

      • 我一直想知道事件如何能像内联点击一样高效(性能方面)。我想他们一定更难追踪?
      • 取决于你的类命名约定,如果约定有意义,那么它会像 onclicks 一样容易找到
      【解决方案8】:

      如果您不想将任何参数传递给 onclick 函数,只需使用event.target 来获取点击的元素:

      <button id="1" onClick="reply_click()"></button>
      <button id="2" onClick="reply_click()"></button>
      <button id="3" onClick="reply_click()"></button>
      
      function reply_click()
      {
          // event.target is the element that is clicked (button in this case).
          console.log(event.target.id);
      }
      

      【讨论】:

        【解决方案9】:

        使用纯 javascript,您可以执行以下操作:

        var buttons = document.getElementsByTagName("button");
        var buttonsCount = buttons.length;
        for (var i = 0; i < buttonsCount; i += 1) {
            buttons[i].onclick = function(e) {
                alert(this.id);
            };
        }​
        

        查看JsFiddle

        【讨论】:

        • 您的代码显示:Uncaught TypeError: Cannot set property 'onclick' of undefined
        • 那是因为你的 html 中没有按钮
        【解决方案10】:
        <button id="1" onClick="reply_click()"></button>
        <button id="2" onClick="reply_click()"></button>
        <button id="3" onClick="reply_click()"></button>
        
        function reply_click()
        {
           console.log(window.event.target.id)
        }
        

        【讨论】:

          【解决方案11】:

          你可以这样做:

          <input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
          <script type="text/javascript">
             function showId(obj) {
                  var id=obj;
                  alert(id);
             }
          

          【讨论】:

          • 你可以删除 var id=obj; 并只使用 alert(obj);
          • 我认为这应该是公认的答案,并且“(this.id)”刚刚在 FF、IE 和 Chrome 中为我工作。
          【解决方案12】:

          按钮 1 按钮 2 按钮 3

          var reply_click = function() { 
               alert("Button clicked, id "+this.id+", text"+this.innerHTML); 
          } 
          document.getElementById('1').onclick = reply_click; 
          document.getElementById('2').onclick = reply_click; 
          document.getElementById('3').onclick = reply_click;
          

          【讨论】:

            【解决方案13】:
             <button id="1"class="clickMe"></button>
            
            <button id="2" class="clickMe"></button>
            
            <button id="3" class="clickMe"></button>
            
            
            
            $('.clickMe').live('click',function(){
            
            var clickedID = this.id;
            
            });
            

            【讨论】:

              【解决方案14】:

              对不起,它的答案迟了,但如果你这样做真的很快:-

              $(document).ready(function() {
                $('button').on('click', function() {
                   alert (this.id);
                });
              });
              

              这会获取点击的任何按钮的 ID。

              如果您只想获取在某个位置单击的按钮的值,只需将它们放入容器中,如

              <div id = "myButtons"> buttons here </div>
              

              并将代码更改为:-

               $(document).ready(function() {
                    $('.myButtons button').on('click', function() {
                       alert (this.id);
                    });
                  });
              

              希望对你有帮助

              【讨论】:

              • 我认为 myButtons 是一个 id,你在 jquery 中使用它作为类选择器,带有点(。)我认为这应该以 # 开头。
              【解决方案15】:

              这将记录被点击元素的 id:addFields。

              <button id="addFields" onclick="addFields()">+</button>
              
              <script>
              
              function addFields(){ 
                  console.log(event.toElement.id)
              }
              
              </script>
              

              【讨论】:

                【解决方案16】:

                虽然晚了 8 年多,但在回复@Amc_rtty 时,为了从(我的)HTML 中动态生成 ID,我使用 php 循环的索引来增加按钮 ID。我将相同的索引连接到输入元素的 ID,因此我最终得到了 id="tableview1" 和 button id="1" 等等。

                $tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";
                

                在 javascript 中,我将按钮单击存储在一个变量中并将其添加到元素中。

                function loadDoc(e) {
                  var btn = e.target.id;
                  var xhttp = new XMLHttpRequest();
                  var page = document.getElementById("tableview"+btn).value;
                  
                  //other Ajax stuff
                  }
                

                【讨论】:

                  【解决方案17】:

                  这是对Prateek answer 的改进——事件是通过参数传递的,所以reply_click 不需要使用全局变量(并且到目前为止还没有正文显示此变体)

                  function reply_click(e) {
                    console.log(e.target.id);
                  }
                  <button id="1" onClick="reply_click(event)">B1</button>
                  <button id="2" onClick="reply_click(event)">B2</button>
                  <button id="3" onClick="reply_click(event)">B3</button>

                  【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-01-21
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-09-07
                  相关资源
                  最近更新 更多