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