简体   繁体   English

获取clicked元素的id而不在html中放入任何js代码

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

I need to get the ID of an element that was clicked, but i need to to keep all my js and html separate. 我需要获取被点击的元素的ID,但我需要将所有js和html分开。 normally id just use 'this.id' in the html. 通常id只是在html中使用'this.id'。 Any other ways? 还有其他方法吗?

This is what e.target is for. 这就是e.target的用途。 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. 您可以在任何地方添加事件侦听器,只要允许click事件冒泡到它(默认情况下会发生),您就可以捕获它。 A basic example: 一个基本的例子:

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

Clicking on each will alert its id. 单击每个将提醒其ID。 Hope this helps :) 希望这可以帮助 :)

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

EDIT 编辑

http://jsfiddle.net/95NZ8/ http://jsfiddle.net/95NZ8/

Try something like this: 尝试这样的事情:

$(document).ready(function () {
    $("#someWrapper").each(function () {
        $(this).on('click', function () {
            alert(this.id);
        });
    });
});
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);
} 

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

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