无法将变量传递给事件侦听器

时间:2019-11-19 18:18:45

标签: javascript html

// display all movies in local storage
function displayMovie() {
    console.log("call dispal");
    let moviePanel = document.getElementById("movie-panel");
    for (i; i < movieStorage.length; i++) {
        let title = movieStorage[i].title;
        let year = movieStorage[i].year;
        let rating = movieStorage[i].rating;
        console.log(i,"    " ,movieStorage.length)
        appendMovie(i, title, year, rating);
    }
}


function appendMovie(i, title, year, rating) {
    console.log("appendMovie index, ", i);
    let template = document.querySelector("#entry-temp");
    let tempNode = template.content.cloneNode(true); 
    tempNode.querySelector("#li-movie-title").innerHTML = title;
    tempNode.querySelector("#li-movie-year").innerHTML = year;
    tempNode.querySelector("#li-movie-rating").innerHTML = "Rated: "+rating;
    tempNode.querySelector('#movie-edit').addEventListener("click", function(e, i) { editMovie(i, title, year, rating);});
    let moviePanel = document.getElementById("movie-panel");
    moviePanel.appendChild(tempNode);
}

function editMovie(index, title, year, rating) {
    console.log("index   ", index);
    console.log("title   ", title);
    to_be_replace = index;

    document.getElementById("add-dialog").show();
    document.getElementById('request-save').removeEventListener("click", saveMovieTemp);
    document.getElementById('request-save').addEventListener("click", saveEditMovieTemp);
    document.getElementById("movie-title").value = title;
    document.getElementById("movie-year").value = year;
    document.getElementById("movie-rating").value = rating;
}

因此,基本上,我希望函数editMovie记住索引i。 因此,下次按下按钮时,可以使用对应的i(创建按钮时的那个按钮)。

但是,如控制台日志所示,标题已正确保存,但索引未定义。真是奇怪。

有人知道原因吗?

谢谢! enter image description here

1 个答案:

答案 0 :(得分:1)

您正在遮蔽外部i

tempNode.querySelector('#movie-edit').addEventListener("click", function(e, i) { 
    editMovie(i, title, year, rating);
});

尝试

tempNode.querySelector('#movie-edit').addEventListener("click", function(e) { 
    editMovie(i, title, year, rating);
});

相反。