简体   繁体   中英

Get the specific div id from an onclick event (Pure JS no Jquery)

When I try the code referenced in SO #1 , I get the console logging a blank string:

installChoices() {
        var choices = this.game.page.options;
        for (var i = 0; i < choices.length; i++) {
            var choice = choices[i];
            var choiceDiv = document.createElement("choice" + i);
            choiceDiv.innerText = choice[0];
            choiceDiv.onclick = function() {
                console.log(this.id);
            }
            this.choicesContainer.appendChild(choiceDiv);
        }

    }

I want to bind to my class function clicked

installChoices() {
        var choices = this.game.page.options;
        for (var i = 0; i < choices.length; i++) {
            var choice = choices[i];
            var choiceDiv = document.createElement("choice" + i);
            choiceDiv.innerText = choice[0];
            choiceDiv.onclick = this.clicked;
            this.choicesContainer.appendChild(choiceDiv);
        }

    }

    clicked(e) {
        console.log(e.parentNode); //this is undefined
        console.log(e.srcElement);
    }

But that shows undefined. When I log srcElement, I get the full element

<choice0>path 1</choice0>

I want to get just the div id when I click, so I can parse that and do logic.

I'd recommend the following approach, as it is the standard:

//assign the event
choiceDiv.addEventListener('click', clicked)

//define the listener
function clicked(event) {
    console.log(event.currentTarget)
}

update:

I'm tempted to offer a fix to your code, because I don't think you're achieving what are you trying to actually do:

function installChoices() {
    var choices = this.game.page.options;
    for (var i = 0; i < choices.length; i++) {
        var choice = choices[i];
        var choiceDiv = document.createElement("div");
        choiceDiv.id = "choice" + i;
        choiceDiv.innerText = choice[0];
        choiceDiv.addEventListener("click", clicked);
        this.choicesContainer.appendChild(choiceDiv);
    }
}

function clicked(ev) {
    console.log(ev.currentTarget.id); //this will log "choice0"
}

Your "clicked" function are receiving an Event rather than a HTML Element. This is the default behavior when an onClick event triggered.

The click event have a srcElement property, indicating the source element the click event occurred upon. This event object have no parentNode property.

Use e.srcElement.parentNode instead.

BTW, in the SO #1 example, it assign "showIt(this)" to onClick, so browser pass "this", the target element rather than the event object, to the onClick function.

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