当我单击此处并存储在数组中时,试图获取按钮的值? 知道我做错了什么吗?



我试图能够单击并选择div内的四个按钮之一。div 是五个之一 - 所以当我单击时,我只想检查确切的按钮和受属性更改影响的正确div 按钮嵌套在div 内,如下所示。 我可以使用事件处理程序来确认单击哪个div im,然后使用 if 语句从那里进行控制吗?

我遇到的最后一个问题是我想将 innerHTML 推送到一个数组然后检查,但我不断收到未定义的错误

.HTML。。。。。。。。。。

<div class="rightMain" id="q1box">
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1A" value="1">The Marauder</button>
</div>
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1B" value="2">The Black Pearl</button>
</div>
</div>

打字稿/JS....

var userGuess:[{}];       ///can i just initilize an array and then push the innerhtml into it?
var answers: [{}];

question1.addEventListener("click", checkq1)
function checkq1(){
if (first.onclick)
{
first.setAttribute("style", "background-color: yellow;")
second.setAttribute("style", "background-color: grey;")
third.setAttribute("style", "background-color: grey;")
fourth.setAttribute("style", "background-color: grey;")
userGuess.push(first.innerHTML)
}
if (second.onclick)
{
first.setAttribute("style", "background-color: grey;")
second.setAttribute("style", "background-color: yellow;")
third.setAttribute("style", "background-color: grey;")
fourth.setAttribute("style", "background-color: grey;")
userGuess.push(second.innerHTML)
}
etc..... 

任何帮助将不胜感激!

我得到的错误与我的数组有关....

index.ts:59 未捕获的类型错误:无法读取未定义的属性"toString" at HTMLDivElement.checkq1 (index.ts:59(

您可以获得所有未选择的答案并为其获取 css,希望对您有所帮助

const answerBtn = document.getElementsByClassName('answerButton');
for (var i = 0; i < answerBtn.length; i++) {
answerBtn[i].addEventListener('click', getAnswer, false);
}
function getAnswer() {
const selectAnswer = this;
selectAnswer.setAttribute('style', 'background-color: yellow;');
const parent = this.parentElement.parentElement;
const notSelectedAns = [];
for (i = 0; i < parent.children.length; i++) {
if (parent.children[i].firstElementChild !== selectAnswer) {
notSelectedAns.push(parent.children[i].firstElementChild);
}
}
for (i = 0; i < notSelectedAns.length; i++) {
notSelectedAns[i].setAttribute('style', 'background-color: grey;');
}
}
<div class="rightMain" id="q1box">
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1A" value="1">The Marauder</button>
</div>
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1B" value="2">The Black Pearl</button>
</div>
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1C" value="3">The Black Pearl</button>
</div>
<div class="answerButtonBox">
<button type="button" class="answerButton" id="q1D" value="4">The Black Pearl</button>
</div>
</div>

相关内容

最新更新