我在“this”中有一个元素如何获得其id的值(和类的值)?
alert(this.id) ;
返回undefined。
答案 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)
您需要将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.