繁体   English   中英

onClick 获取被点击按钮的ID

[英]onClick to get the ID of the clicked button

如何找到被点击的按钮的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()
{
}

您需要将 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发送,您可以在您的函数中使用它。 在这里查看它的实际效果。

一般来说,如果将代码和标记分开,事情会更容易组织起来。 定义所有元素,然后在 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:我知道现在已经晚了,但可能对未来的人有帮助:

在 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'。

(我认为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);
    }
}

...但这需要您对古怪的事件模型相对适应。

<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;
}
<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>

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

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

仅限 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函数,它也无法在其中运行。

如果你不介意它的缺点,你总是可以用document.write替换insertHTML

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

资料来源:

如果您不想将任何参数传递给 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);
}

使用纯 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 上检查

你可以简单地这样做:

<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);
   }

<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)
}

按钮 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;
 <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;

});

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

$(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);
      });
    });

我希望这会有所帮助

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

<button id="addFields" onclick="addFields()">+</button>

<script>

function addFields(){ 
    console.log(event.toElement.id)
}

</script>

虽然晚了 8 年多,为了从(我的)HTML 获取动态生成的 ID,我还是使用了 php 循环的索引来增加按钮 ID,以回复@Amc_rtty。 我将相同的索引连接到输入元素的 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
  }

这是Prateek 答案的改进 - 事件是通过参数传递的,因此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>

第一种方式:使用this发送触发元素

<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>

<script>
  function myFun(trigger_element)
  {
      // Get your element:
      var clicked_element = trigger_element

      alert(clicked_element.id + "Was clicked!!!");
  }
</script>

这种方式发送一个类型的对象: HTMLElement并且你得到元素本身。 您不需要关心元素是否具有 id 或任何其他属性。 它本身就可以正常工作。


第二种方式:使用this.id发送触发元素 id

<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>

<script>
  function myFun(clicked_id)
  {
      // Get your element:
      var clicked_element = document.getElementById(clicked_id)

      alert(clicked_id + "Was clicked!!!");
  }
</script>

这种方式发送一个类型的对象: String并且您不会获得元素本身。 所以在使用之前,你需要确保你的元素已经有了一个id。

您不能自己发送元素 id,例如onClick="myFun(btn02)" 它不是干净的代码,它会使您的代码失去功能。


在你的情况下:

<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>

暂无
暂无

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

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