Descriere:Cuvintele speciale "this" si "target" pot fi utilizate in evenimente JavaScript pentru a obtine elementul asociat la evenimentul inregistrat.
Download:
Autor:
Sursa (Link-ul oficial): Propria parere:Nu l-am incercat.
Tutorialul:
- "this" - reprezinta obiectul la care a fost inregistrat evenimentul in codul javascript.
- "target" - e o proprietate pt evenimente. "e.target" este elementul care declanseaza evenimentul (pe care se executa actiunea).
• Ca sa puteti utiliza proprietatea "target" trebuie sa adaugati un parametru la functia cu evenimentul.
Sintaxa:
Cod: Selectaţi tot
obiect.eveiment = function(e) {
// aici se poate folosi e.target
}- Iata un exemplu. Un DIV #parinte cu un DIV #copil in el. Eveniment onclick inregistrat la #parinte, si se obtine ID-ul elementului returnat de "this" si "e.target".
Cod: Selectaţi tot
<!doctype html>
<html lang="ro">
<head>
<meta charset="utf-8" />
<title>Exemplu this si target</title>
<style type="text/css">
#parinte {
height: 7em;
background: #00da01;
padding: 1em;
}
#copil {
height: 80%;
margin: 0.5em 1.5em;
background: #8889fe;
}
</style>
</head>
<body>
<div id="parinte">Parinte
<div id="copil">Copil</div>
</div>
<script type="text/javascript">
document.getElementById('parinte').onclick = function(e) {
var id1 = this.id;
var id2 = e.target.id;
alert('this = '+ id1 +'\n e.target = '+ id2);
}
</script>
</body>
</html>- In urmatorul exemplu fereastra alert e afisata doar la clic pe DIV-ul Parinte.
Cod: Selectaţi tot
<!doctype html>
<html lang="ro">
<head>
<meta charset="utf-8" />
<title>Exemplu this si target</title>
<style type="text/css">
#parinte {
height: 7em;
background: #00da01;
padding: 1em;
}
#copil {
height: 80%;
margin: 0.5em 1.5em;
background: #8889fe;
}
</style>
</head>
<body>
<div id="parinte">Parinte
<div id="copil">Copil</div>
</div>
<script type="text/javascript">
document.getElementById('parinte').onclick = function(e) {
if(this === e.target) {
alert(this.id);
}
}
</script>
</body>
</html>
