简体   繁体   中英

Why can't I add an event listener to the div?

I have an object, which has a method that creates divs, then assigns them an on-click event, but I also want to assign them an onkeypress event, but it won't let me do it...

This is the method which creates divs. It works fine.

populateSquares(){
    let relatedTagToPopulation = document.getElementById("questionp");
    let whatTextIs = relatedTagToPopulation.textContent;
    for (let u=0;u<this.stemQuestions.length;u++){
        if (this.stemQuestions[u]==whatTextIs){
            var populateSquaresPertinentInt = u;
        }
    }
    for  (let i=0;i<this.stemAnswers.length;i++){
        if (i==populateSquaresPertinentInt){
            let numberOfSquaresToAdd = this.stemAnswers[i].length;
            for (let j=0;j<numberOfSquaresToAdd;j++){
                let elToAdd = document.createElement("div"); 
                elToAdd.id="ans"+j+"";
                elToAdd.className="lans";
                elToAdd.onclick= hangmanGame.selectThisSquare;
                console.log(elToAdd);
                let elToAddInto = document.getElementById("answeri"); 
                elToAddInto.appendChild(elToAdd); 
            }
        }
    }
},

This is the method that adds some properties to the div and also an event listener

selectThisSquare(e){
    let currentElementId = e.target.id;
    document.getElementById(currentElementId).style.cursor = "text";
    document.getElementById(currentElementId).style.backgroundColor = "#557a95";
    document.getElementById(currentElementId).onkeydown = hangmanGame.textInputHandler;
    console.log(e.target.id);
    let x = hangmanGame.giveCurrentQuestionAndWord();
    let xs = x[1];
    hangmanGame.deselectAllOtherSquares(currentElementId,xs);
},

This is the method that is supposed to trigger when the key is pressed, but nothing is triggered.

textInputHandler(){
    console.log(4);
},

A div by default isn't "selectable" and thus it won't react to any keydown events. However, you can make it selectable by adding tabindex="0" to the div. This way it will become focusable when you click on it, which then allows the onkeydown event to trigger.

See working example below:

 const game = { addKeyDownListener() { document.getElementById("txt").onkeydown = game.handleTextInput }, handleTextInput() { console.log(4); } } game.addKeyDownListener(); 
 #txt { height: 100px; width: 100px; border: 1px solid black; outline: none; /* add to hide outline */ } 
 <div type="text" id="txt" tabindex="0"></div> 

Note: By default adding a tabindex will give your div a blue outline once selected. To remove this add the css outline: none .

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