简体   繁体   中英

Referring to the calling object in JavaScript using addEventListener

I'm new to JavaScript/HTML/CSS and I can't spot the mistake I'm doing in this JavaScript function. Out teacher told us to use the addEventListener method cause it has some notable advantages.

This is my entire script with the problematic function

 var espandi = function (e) {
    var toHide = document.getElementsByClassName("optional");
    for (var index = 0; index < toHide.length; index++)
        toHide[index].style.display = "none";
    var toShow = e.target.getElementsByClassName("optional");
    for (index = 0; index < toShow.length; index++)
        toShow[index].style.display = "block";
}
var expansibleObjects = document.getElementsByClassName("singleresult");
for (var index = 0; index < expansibleObjects.length; index++)
    expansibleObjects[index].onclick = espandi();

The fact is the line e.target.addEventListener() gets me an error of this type Uncaught TypeError: Cannot read properties of undefined (reading 'getElementsByClassName'). On the contrary if i set the function with the property "onclick" directly on the element the function works perfectly. SO i think the problem it's about referring to the calling object using "e.target"

You are calling espandi instead of assign it to onclick handler.

So you need to remove the () and do expansibleObjects[index].onclick = espandi;

Anyway in your question I don't see any e.target.addEventListener() so when you say The fact is the line e.target.addEventListener() gets me an error I don't understand what you mean, maybe you have to add more code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM