JavaScript and jquery get the element that triggers the event

Source: Internet
Author: User

A very simple problem, but because of the main idea, often forget to deal with, causing the program to run an error.

<!DOCTYPE HTML><HTML>    <Head>        <MetaCharSet= "Utf-8" />        <title></title>    </Head>    <Body>        <ul>            <Li>                <ul>                    <Li>Listone</Li>                    <Li>Listtwo</Li>                    <Li>Listthree</Li>                </ul>            </Li>        </ul>        <Script>            varOul=document.getElementsByTagName ('ul')[0]; varALi=Oul.getelementsbytagname ('Li'); varI=0;  for(i=0; I<Ali.length;i++) {Ali[i].onclick=function() {alert ( This. InnerHTML); }            }        </Script>    </Body></HTML>

I meant to pop up Li's content when I clicked on Li. such as "Listone", "Listtwo", "Listthree".

But the code above does not work as expected.

When I click on Listtwo Li, this is the case:

Not yet, click OK, and a frame pops up:

This frame is not what we expect to pop up. Why would he pop it?

Look back at the code, this is because Listone,listtwo,listthree is located in the parent element of the UL, is also an Li, this Li is also added to the Click event, pop his own innerhtml.

How to solve?

As long as we tell JavaScript, just pop up the content of the Li that we clicked on. Is the li that triggered the click event. The code is as follows:

var oul=document.getelementsbytagname (' ul ') [0]; var ali=oul.getelementsbytagname (' li '); var i=0;  for (i=0;i<ali.length;i++) {    Ali[i].onclick=function(EV) {    var e= ev| | window.event;//getting events     var ele=e.target| | e.srcelement;//Gets the element that triggered the event
if (This===ele)//If this element is the element that triggered the event alert (ele.innerhtml);//Popup his content }}

Problem solving.

JavaScript and jquery get the element that triggers the event

Related Article

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.