javascript 获取被点击元素的 id 而不在 html 中放置任何 js 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10270824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:15:13  来源:igfitidea点击:

get id of clicked element without putting any js code in the html

javascripthtmljavascript-events

提问by wazzaday

I need to get the ID of an element that was clicked, but i need to to keep all my js and html separate. normally id just use 'this.id' in the html. Any other ways?

我需要获取被点击的元素的 ID,但我需要将我所有的 js 和 html 分开。通常 id 只是在 html 中使用“this.id”。还有其他方法吗?

回答by Darragh Enright

This is what e.targetis for. You can add an event listener anywhere you want, as long as the click event is allowed to bubble up to it (which happens by default) you can catch it. A basic example:

e.target就是为了。你可以在任何你想要的地方添加一个事件监听器,只要允许点击事件冒泡到它(默认情况下发生)你就可以捕获它。一个基本的例子:

document.addEventListener('click', function(e) {
    alert(e.target.id);
});

Clicking on each will alert its id. Hope this helps :)

单击每个将提醒其 ID。希望这可以帮助 :)

<button id="foo">foo</button>
<button id="bar">bar</button>
<button id="baz">baz</button>

EDIT

编辑

http://jsfiddle.net/95NZ8/

http://jsfiddle.net/95NZ8/

回答by Petr Felzmann

Try something like this:

尝试这样的事情:

$(document).ready(function () {
    $("#someWrapper").each(function () {
        $(this).on('click', function () {
            alert(this.id);
        });
    });
});

回答by bhv

window.onclick = e => {
    console.log(e.target.id);
}

to get element, tagname, classname , other attributes

获取元素、标记名、类名、其他属性

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.tagName);
    console.log(e.target.className);
    console.log(e.target.id);
}