In JavaScript development, it is often necessary to get the target object that triggers an event. Enables different business processing based on the target object. The following shows the event target object that gets the trigger event through JavaScript. As follows:
JS Code
12345678910 |
window.onload =
function
(){
var
obj = document.getElementById(
"test"
);
obj.onclick =
function
(event){
// W3C的event对象直接通过函数参数传递过来(arguments[0])
// IE的event对象绑定到window对象上面
var
evt = event || window.event;
alert(evt);
};
};
|
HTML code
12345678910111213141516171819202122232425262728 |
<title>get target</title>
<script type=
‘text/javascript‘
>
window.onload =
function
(){
var
obj = document.getElementById(
"test"
);
obj.onclick =
function
(event) {
// 获取事件对象
var
evt = event || window.event;
// 获取事件触发的目标对象
// W3C标准(非IE): evt.target
// IE:evt.srcElement
var
src = evt.target || evt.srcElement;
// 当点击div(非h3)标签上显示DIV,点击h3标签上显示H3
alert(src.tagName);
};
};
</script>
<body>
<div style=
‘height: 200px; width: 200px; background-color: green; padding: 30px;‘
id=
"test"
>
‘background-color: red;‘
>点击我......
</div>
<body>
|
JavaScript gets the event object and the target object