将元素插入DOM后访问元素ID

时间:2018-10-18 11:39:26

标签: javascript

将提交按钮插入Dom并单击后,我想访问它。但是单击提交按钮后,我得到的是空值。

function getUserChoice(userChoice){
let =  elChoices = document.getElementsByName('choices-' + (current + 1));
for (let i = 0; i < elChoices.length; i++) {
    if (elChoices[i].checked) {
        userChoice = elChoices[i].value;
        elChoices[i].checked = false;
        return userChoice;   
    }
}
alert("Please select an answer before continuing");
return false;

}

let Question = function(question, answers,correct){
this.question = question;
this.answers = answers;
this.correct = correct;

}

//检查答案

Question.prototype.checkAnwers = function(ans,callback){
    let sc;
    if (ans === this.correct) {
        console.log('Correct answer');
        sc = callback(true);
    }else{
        console.log('Wrong answer')
        sc = callback(false);
    }
    this.displayScore(sc);       

}

//显示分数

Question.prototype.displayScore = function(score){
console.log('Your current score is: ' + score);
console.log('---------------------------------')

}

function score(){
let sc = 0;
return function(correct){
    if (correct) {
        sc++;
    }
    return sc;
}   

}

//从函数构造函数创建新对象

let q1 = new Question('Atom is the smallest particle of.....?',['Matter','Volume','Area','Density'],'A');

让q2 = new Question('原子序数为16的元素是?',['硅','硫','钠','锂'],'B'); 让q3 =新问题(“最容易学习的语言之一是',['Javascript','Python','Java','C#'],'C'); 让问题= [q1,q2,q3];

///使用占位符文本创建html字符串

let html,newhtml,element;

element =“ .field”; html ='%id%。 %question%

%option1%
%option2%
%option3%
%option4%
提交'

///用实际数据替换占位符文本

Question.prototype.displayQuestion = function(){
newhtml = newhtml.replace('%question%',this.question);
for (let index = 0; index < this.answers.length; index++) {
    newhtml = newhtml.replace('%option1%',this.answers[index]);
    newhtml = newhtml.replace('%option2%',this.answers[index + 1]);
    newhtml = newhtml.replace('%option3%',this.answers[index + 2]);
    newhtml = newhtml.replace('%option4%',this.answers[index + 3]);
}

}

let keepScore = score();

for (let index = 0; index < questions.length; index++) {
let current = 0;
if (index === current) {
    current = index + 1;
    newhtml = html.replace('%id%',current);
    questions[index].displayQuestion();
    newhtml = newhtml.replace('%id%',current);
    document.getElementById('submit-'+ current).addEventListener('click', function(){
        questions[current].checkAnwers(getUserChoice,keepScore)
    })
}    

}

//将元素插入Dom

document.querySelector(element).insertAdjacentHTML('beforeend',newhtml);

1 个答案:

答案 0 :(得分:0)

要在页面首次加载时在DOM中不存在的任何元素上添加事件侦听器,您需要event delegation

在事件委托中,将事件侦听器设置在父元素上,在这种情况下,它将是按钮的父元素。在事件侦听器代码中,您将需要检查当前事件是否在该按钮上触发。您可以使用作为参数传递给事件侦听器方法的事件对象来做到这一点。

有关其工作原理的更多信息,请参阅此tutorial