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

当前回答

使用纯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”。

其他回答

如何做到这一点没有内联JavaScript或外部库

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

现代浏览器(2015+)

在文件完成加载之前进行操作。 很能干的人。 把JS和HTML分开。 JS在<head>

const Listen = (doc) => { return { on: (type, selector, callback) => { doc.addEventListener(type, (event)=>{ if(!event.target.matches(selector)) return; callback.call(event.target, event); }, false); } } }; Listen(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函数在它中不起作用,尽管它在我的所有浏览器中都可以工作。

你总是可以用document替换insertHTML。如果你不介意它的缺点,那就写吧

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

来源:

document.write的替代方案是什么? 在JavaScript中检查元素是否包含类? event.preventDefault()函数在IE中无法工作 https://gist.github.com/eduardocereto/955642

一般来说,如果将代码和标记分开,事情就更容易保持有序。定义所有元素,然后在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”。

你可以简单地这样做:

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