有没有办法捕获变量中的dom元素的id?

时间:2013-11-20 11:45:52

标签: html dom this

我在“this”中有一个元素如何获得其id的值(和类的值)?

alert(this.id) ; 

返回undefined。

2 个答案:

答案 0 :(得分:1)

首先,您应该检查this是否真的是您的目标元素,而不是全局window对象。让我说明一下我的建议:

function foo() {
  if (this === window) {
    alert("'this' is actually 'window'");
  } else {
    alert("'this' is not 'window'");
  }
}

foo(); // will alert: 'this' is actually 'window'

但:

document.onclick = foo;
// every mouse click will produce alert: 'this' is not 'window'

无论如何,我建议您使用Firebug / Chrome控制台来检查this对象的真实价值:

console.log(this); // will reveal you the real nature of _this_ ;-)

答案 1 :(得分:0)

可能duplicate for this

您需要将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,您可以在功能中使用该{{1}}。 See it in action here.