简体   繁体   English

JavaScript事件未添加到DOM

[英]JavaScript Events not adding to the DOM

As an exercise I have to do a little online bike reservation app. 作为一项练习,我必须做一些在线自行车预订应用程序。 This app begins with a header which explains how to use the service. 该应用程序以标题开头,说明如何使用该服务。 I wanted this tutorial be optional so I wrote a welcome message in HTML and if the user doesn't have a var in his cookies saying he doesn't want to see the tutorial again, the welcome message is replaced by a slider that displays the information. 我希望本教程是可选的,所以我用HTML编写了一条欢迎消息,如果用户的cookie中没有var表示不想再看该教程,则欢迎消息将被显示为信息。

To achieve that is fetch a JSON file with all the elements I need to build the slider (three divs : the left one with an arrow image inside, the central one where the explanations occur and the right one with another arrow). 要实现这一点,需要获取一个我需要构建滑块的所有元素的JSON文件(三个div:左侧是一个带有箭头图像的区域,中间是一个进行解释的位置,右侧是另一个箭头的位置)。 Furthermore I want to put "click" events on the arrows to display next or previous slide. 此外,我想在箭头上放置“单击”事件以显示下一张或上一张幻灯片。 However, when I do so, only the right arrow event works. 但是,当我这样做时,只有右箭头事件起作用。 I thought of a closure problem since it is the last element to be added to the DOM that keeps its event but tried many things without success. 我想到了一个关闭问题,因为它是最后添加到DOM中的元素,它可以保持事件发生,但是尝试了很多事情却没有成功。 I also tried to add another event to the div that works ("keypress") but only the click seems to work. 我还尝试向div添加另一个可以工作的事件(“ keypress”),但只有单击似乎有效。 Can you look at my code give me an hint on what is going on? 您能否看一下我的代码,以提示我发生了什么事?

Here is the init function of my controller: 这是我的控制器的初始化函数:

init: function() {
    var load = this.getCookie();
    if(load[0] === ""){
        viewHeader.clearCode();
        var diapoData = ServiceModule.loadDiapoData("http://localhost/javascript-web-srv/data/diaporama.json");
        diapoData.then(
            (data) => {
                // JSON conversion
                modelDiapo.init(data);           
                // translation into html
                controller.initElementHeader(modelDiapo.diapoElt[0]);
                controller.hideTuto();
            }, (error) => {
                console.log('Promise rejected.');
                console.log(error);
            });
    } else {
        viewHeader.hideButton();
        controller.relaunchTuto();
    }
}

There is a closer look at my function translating the JSON elements into HTML and adding events if needed : 我们仔细研究了将JSON元素转换为HTML并在需要时添加事件的函数:

initElementHeader: function(data){
    data.forEach(element => {
        // Creation of the new html element
        let newElement = new modelHeader(element);
        // render the DOM
        viewHeader.init(newElement);
    });
}

NewElement is a class creating all I need to insert the HTML, viewHeader.init() updates the DOM with those elements and add events to them if needed. NewElement是一个类,它创建所有我需要插入HTML的类,viewHeader.init()使用这些元素更新DOM并在需要时向其添加事件。

init: function(objetElt){
    // call the render
    this.render(objetElt.parentElt, objetElt.element);
    // add events
    this.addEvent(objetElt);
},

Finally the addEvent function: 最后是addEvent函数:

addEvent: function(objet){
    if(objet.id === "image_fleche_gauche"){
        let domEventElt = document.getElementById(objet.id);
        domEventElt.addEventListener("click", function(){
            // do things
        });
    }
    else if(objet.id === "image_fleche_droite"){
        let domEventElt = document.getElementById(objet.id);
        domEventElt.addEventListener("click", function(){
            // do stuff
        });
    };
},

I hope being clear enough about my problem. 我希望对我的问题足够清楚。 Thank You. 谢谢。

Ok, I found the problem, even if the element was actually created, it somehow stayed in the virtual DOM for some time, when the "getElementById" in "addEvent" was looking for it in the real DOM it didn't find the target and couldn't add the event. 好的,我发现了问题,即使元素是实际创建的,它也以某种方式停留在虚拟DOM中一段时间​​,当“ addEvent”中的“ getElementById”在真实DOM中寻找它时,却找不到目标并且无法添加事件。 This problem didn't occur for the last element since there was nothing else buffering in the virtual DOM. 最后一个元素没有发生此问题,因为虚拟DOM中没有其他缓冲。

On conclusion I took out the function adding events out of the forEach loop and created another one after the DOM is updated to add my events. 最后,我从forEach循环中删除了添加事件的函数,并在DOM更新以添加事件后创建了另一个函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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