是否有可能从调用JavaScript函数中获得JavaScript触发事件而不传递任何事件参数?
下面是示例代码:<html>
<head>
<script>
function myFunction()
{
// How I will get from here the fired event ??
}
</script>
</head>
<body>
<p id="paragraghhh" onclick="myFunction()">
Click on this paragraph. An alert box will
show which element triggered the event.
</p>
</body>
</html>
在JavaScript函数中,您可以引用this。事件属性。
例如,function myFunction(){
alert(this.event.type);
}
警告JS事件,在本例中是'click'
试试这个:
onclick="myFunction(event)"
JS:
function myFunction(e)
{
console.log(e.target);
}
或:
onclick="myFunction.call(this)"
JS:
function myFunction()
{
console.log(this);
}
更好的解决方案:
document.getElementById('paragraghhh').addEventListener('click', function(){
console.log(this);
});
把HTML改成
<p id="paragraghhh" onclick="myFunction(event)">
Click on this paragraph. An alert box will
show which element triggered the event.
</p>
和JS
function myFunction(event)
{
// Handle event
}