Target property and cancel bubbling event under the Js:event object

Source: Internet
Author: User

1.target

By getting DOM elements

var box = document.getElementById ("box");
Document.box.onclick = function () {
alert (123);//123
}

Target method under the event object: Gets the target of the event, without document.getElementById ("box") to obtain the target;

Under the
Document.onclick = function (evt) {
var e = evt | | window.event;
alert (e.target.tagname); DIV IE7 below for Undefind

}

For srcelement under IE

Document.onclick = function (evt) {
var e = evt | | window.event;
Alert (typeof e.srcelement); Div
}

Compatible with all browsers

function Gettarget (evt) {
var e = evt | | window.event;
return E.target | | E.srcelement;
}

Document.onclick = function (evt) {
Alert (Gettarget (EVT));
}

2. Bubbling Event

Document.onclick = function () {
Alert (' Document ');
};
Document.documentElement.onclick = function () {
Alert (' HTML ');
};
Document.body.onclick = function () {
Alert (' body ');
};
document.getElementById ("box"). onclick = function () {
Alert ("div");
}
document.getElementsByTagName ("input") [0].onclick =function (evt) {
var e = evt | | window.event;
E.stoppropagation (); Suppress bubbling events (non-IE7 browsers below)

E.cancelbubble = true; IE7 the following browsers
Setstopbubble (EVT); Cancel bubbling compatible All will only pop up "input", others do not eject.
Alert ("Input");
}

When the button is clicked, the input> div> body> html> document is popped up sequentially, which is caused by a bubbling event.

Cancel bubbling Event stoppropagation ()/cancelbubble

Compatible with all browsers
function Setstopbubble (evt) {
var e = evt | | window.event;
typeof e.stoppropagation = = "function"? E.stoppropagation (): E.cancelbubble = true;

}

  

Target property and cancel bubbling event under the Js:event object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.