获取单击元素的ID,而不在HTML中放入任何js代码 [英] get id of clicked element without putting any js code in the html

查看:117
本文介绍了获取单击元素的ID,而不在HTML中放入任何js代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得被点击的元素的ID,但我需要保持我所有的js和html分开。通常id只是在html中使用'this.id'。任何其他方式?

解决方案

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

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

每次点击都会提醒其ID。希望这有助于:)

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

编辑

http://jsfiddle.net/95NZ8/


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?

解决方案

This is what e.target is 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:

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

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

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

EDIT

http://jsfiddle.net/95NZ8/

这篇关于获取单击元素的ID,而不在HTML中放入任何js代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆