从onclick事件中获取特定的div id(Pure JS no Jquery)



当我尝试SO#1中引用的代码时,控制台会记录一个空白字符串:

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);
        }
    }

我想绑定到我的类函数点击

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);
    }

但这显示出了不确定性。当我登录srcElement时,我会得到完整的元素

<choice0>path 1</choice0>

我想在点击时只得到div id,这样我就可以解析它并进行逻辑处理。

我推荐以下方法,因为它是标准的:

//assign the event
choiceDiv.addEventListener('click', clicked)
//define the listener
function clicked(event) {
    console.log(event.currentTarget)
}

更新:

我很想为你的代码提供一个修复程序,因为我认为你没有实现你想要做的事情:

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"
}

您的"点击"函数接收的是一个事件,而不是HTML元素。这是触发onClick事件时的默认行为。

单击事件具有srcElement属性,指示发生单击事件的源元素。此事件对象没有parentNode属性。

请改用e.srcElement.parentNode。

顺便说一句,在SO#1示例中,它将"showIt(this)"分配给onClick,因此浏览器将"this"(目标元素而非事件对象)传递给onClick函数。

最新更新