如何在事件监听器中正确执行功能?

时间:2019-06-18 23:44:54

标签: javascript event-handling

每次用户单击一个按钮时,该按钮中的字母都会与列表项按钮进行比较。我正在测试我的代码,看来我的javascript文件中checkLetter函数中的代码无法正常工作。

这是我的HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Wheel of Success!</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/styles.css" rel="stylesheet">
  </head>
  <body>
    <div class="main-container">
      <div id="overlay" class="start">
        <h2 class="title">Wheel of Success</h2>
        <a class="btn__reset">Start Game</a>
      </div>

      <div id="banner" class="section">
        <h2 class="header">Wheel of Success</h2>
      </div>

      <div id="phrase" class="section">
        <ul></ul>
      </div>
      <div id="qwerty" class="section">
        <div class="keyrow">
          <button>q</button><button>w</button><button>e</button><button>r</button><button>t</button><button>y</button><button>u</button><button>i</button><button>o</button><button>p</button>
        </div>
        <div class="keyrow">
          <button>a</button><button>s</button><button>d</button><button>f</button><button>g</button><button>h</button><button>j</button><button>k</button><button>l</button>
        </div>
        <div class="keyrow">
          <button>z</button><button>x</button><button>c</button><button>v</button><button>b</button><button>n</button><button>m</button>
        </div>
      </div>

      <div id="scoreboard" class="section">
        <ol>
          <li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
          <li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
          <li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
          <li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
          <li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
        </ol>
      </div>
    </div>
  </body>
  <script src="app.js"></script>
</html>

这是我的Javascript:

let missed=0;
const qwertyID=document.getElementById('qwerty');
const phraseID=document.getElementById('phrase');
const buttonElement=document.getElementsByClassName("btn__reset")[0];
const overLay=document.getElementById('overlay');
phraseArray=["Hey man","What the heck","Western University","Is that cool?","What is that?"];
const ul=document.getElementsByTagName('UL')[0];


//picks random phrase from phraseArray
//breaks phrase into character array
//returns arr---character array to be displayed
function getRandomPhraseAsArray(array) {
    index = Math.floor((Math.random() * array.length))
    let str=array[index];
    let arr=[...str];
    console.log(arr);
    return arr;
}
//appends each character as list items in ul
//takes arr in parameter
function addPhraseToDisplay(characterArray) {
    for (let i=0; i<characterArray.length; i+=1) {
        let char=characterArray[i];
        listItem=document.createElement('LI');
        listItem.textContent=char;
        if (char!==" ") {
            listItem.className="letter";
        }
        ul.appendChild(listItem);   
    }
}

function checkLetter(button) {
    letterFound=button.textContent;
    letter=document.getElementsByClassName('letter');
    for (let i=0;i<letter.length;i+=1) {
        if (letter[i].textContent===letterFound) {
            console.log("hello");
        } else {
            return null;
        }
    }
}


qwertyID.addEventListener('click', (e)=>{
    e.target.className="choosen";
    const button=e.target;
    checkLetter(button);
});


//stores arr (character array) from function into variable 
//inputs variable (character array) into new function
let phraseDisplayed=getRandomPhraseAsArray(phraseArray);
addPhraseToDisplay(phraseDisplayed);

//listener event to button to hide overlay
buttonElement.addEventListener('click', ()=> {
    overLay.style.display="none";
});

如您所见,“ hello”没有输出到控制台。我在checkButton事件侦听器中使用了qwertyID函数,感觉按钮变量的范围一定存在问题。

该项目的说明要求我在我的checkButton函数中输入button元素作为自变量,因此无法更改代码的这一方面。我想知道是否有人可以指出我的问题?

2 个答案:

答案 0 :(得分:0)

当“返回null”时,该函数退出。行执行,因此如果不是按钮列表中的第一行,则退出:

function checkLetter(button) {
  letterFound = button.textContent;
  letter = document.getElementsByClassName('letter');
  for (let i = 0; i < letter.length; i += 1) {
    if (letter[i].textContent === letterFound) {
      console.log("hello");
    } else {
      //return null; //Change THIS
      console.log("not found (yet)");
    }
  }
}

答案 1 :(得分:0)

phraseArray 中的某些单词以大写字母开头。因此,如果用户按下 w ,并且您的代码将其与 W 进行比较,则永远不会得出true。 要解决此问题,您需要先将输入内容转换为小写字母。

letterFound=button.textContent.toLowerCase();

此外,在第一次测试失败后,您的脚本将不会检查其余字母,因为您使用 return null;

从函数中返回

摆脱它,而改用它:

function checkLetter(button) {
  letterFound = button.textContent.toLowerCase();
  letter = document.getElementsByClassName('letter');
  for (let i = 0; i < letter.length; i += 1) {
    console.log(letter[i].textContent)
    if (letter[i].textContent === letterFound) {
      console.log("hello");
    }
  }
}