Dig*_*nta 5 javascript event-handling
是否可以在不传递任何事件参数的情况下从调用的 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>
Run Code Online (Sandbox Code Playgroud)
kar*_*una -1
尝试这个:
onclick="myFunction(event)"
Run Code Online (Sandbox Code Playgroud)
JS:
function myFunction(e)
{
console.log(e.target);
}
Run Code Online (Sandbox Code Playgroud)
或者:
onclick="myFunction.call(this)"
Run Code Online (Sandbox Code Playgroud)
JS:
function myFunction()
{
console.log(this);
}
Run Code Online (Sandbox Code Playgroud)
更好的解决方案:
document.getElementById('paragraghhh').addEventListener('click', function(){
console.log(this);
});
Run Code Online (Sandbox Code Playgroud)