满足按钮单击条件以在 javascript 中显示消息

Satisfying button click condition to bring up a message in javascript

如果我的代码真的很糟糕,请提前道歉,但我只是一个初学者。我想使用按钮创建一个单词搜索谜题。当这个人通过单击我要用按钮组成的所有单词完成查找时,我希望出现一条消息,表明他们已经完成了拼图。所以我在这里创建了一个带有 4 个按钮的示例,但我似乎无法让我的代码工作。单击所有按钮后,我希望消息出现在 div 容器中。我是在正确的轨道上还是偏离了轨道?任何见解将不胜感激!

<html>

      <p onclick="myFunction()" id="1" value=false >Button1</p>
      <p onclick="myFunction()" id="2" value=false >Button2</p>
      <p onclick="myFunction()" id="3" value=false >Button3</p>
      <p onclick="myFunction()" id="4" value=false >Button4</p>

      <div id="demo">Message displays here if all 4 buttons are clicked</div>

<script>
function myFunction(){
  value = true;}

    if(p 1){
        value = true;}

    if(p 2){
        value = true;}

    if(p 3){
        value = true;}

    if(p 4){
        value = true;}
else{
  document.getElementById("demo").innerHTML = "Congratulations you clicked on all of the buttons";}

}
</script>
</html>

一个更简单的方法是使用事件侦听器侦听每个按钮的点击,然后使该按钮的值为真,然后检查所有按钮以查看它们是否都被点击,如果是则输出恭喜留言

HTML

为每个按钮添加了 类 并删除了 onclick 功能

<html>
      <p class='button' id="1" value=false >Button1</p>
      <p class='button' id="2" value=false >Button2</p>
      <p class='button' id="3" value=false >Button3</p>
      <p class='button' id="4" value=false>Button4</p>

      <div id="demo">Message displays here if all 4 buttons are clicked</div>
</html>

JS

window.addEventListener('click', (e)=>{
  var bool = true
  if (e.target.classList.contains('button')) {
    e.target.setAttribute('value', "true")
  }
  buttons = document.querySelectorAll('.button')
  for (let i = 0; i < buttons.length; i++) {
    console.log(buttons[i].getAttribute('value'))
    if (buttons[i].getAttribute('value') == "false") {
      bool = false
    }
  }
  if (bool == true) {
    document.getElementById("demo").innerHTML = "Congratulations you clicked on all of the buttons";
  }
})

我建议这是一个容易理解 javascript 和 html 更好一点的答案:

HTML

<html>
  <body>
    <button onclick="myFunction(event)" name="button1">Button1</button>
    <button onclick="myFunction(event)" name="button2">Button2</button>
    <button onclick="myFunction(event)" name="button3">Button3</button>
    <button onclick="myFunction(event)" name="button4">Button4</button>
    <div id="demo">Message displays here if all 4 buttons are clicked</div>
  </body>
</html>

JS

    var foundButtons = {
      button1: false,
      button2: false,
      button3: false,
      button4: false,
    };

    function myFunction(event) {
      foundButtons[event.target.name] = true;
      for (var button in foundButtons) {
        if (foundButtons.hasOwnProperty(button)) {
          if (!foundButtons[button]) {
            return
          }
        }
      }
      document.getElementById("demo").innerHTML = "Congratulations you clicked on all of the buttons";
    }

这样做是为了让您有一个按钮对象,或者更确切地说,是必须单击才能显示消息的单词。现在,当其中一个按钮被点击时,它的 属性 被设置为 true。然后它遍历属性并以 return 语句结束函数,如果它找到一个 false 值,这意味着有一个按钮没有被点击。当函数没有停止时,它将显示成功消息。

这是我的解决方案。

var set = []; //decalre an empty array

function myFunction(Id) {
  console.log(Id); //the Id will be the vlaue from the button. For example button 1 has an Id of one as passed into by 'myFunction(1)
  if (set.indexOf(Id) == -1) { //here we check to see if the Id number is in the array
    set.push(Id); //if it's not in the array, we add it in
    console.log(set);
    console.log("length: " + set.length);
    if (set.length > 3) { //if the lengthof the array is greater than three, all 4 buttons have been clicked.
      document.getElementById("demo").innerHTML = "Congratulations you clicked on all of the buttons";
    }
  } 
}
<p onclick="myFunction(0)">Button0</p>
<p onclick="myFunction(1)">Button1</p>
<p onclick="myFunction(2)">Button2</p>
<p onclick="myFunction(3)">Button3</p>
<div id="demo">Message displays here if all 4 buttons are clicked</div>

您可以使用按钮的 data attributes 来保持它们的状态 。 (注意:对于更复杂的项目,您可能不想这样做)

此外,像 onclick="myfunction()" 这样将 JS 内联对您的代码有些不利 - 它会鼓励使用全局变量并使 JS 逻辑更难遵循。因此,我展示了使用 IIFE, .querySelectorAll(), and .addEventListener():

的替代方案

// IIFE to keep variables out of the global scope
;(() => {
  // NOTE: These are more flexible when they are arrays (thus, Array.from())
  const btnEls = Array.from(document.querySelectorAll('.js-button'))
  const msgEls = Array.from(document.querySelectorAll('.js-message'))

  const handleButtonClick = ({ target: btnEl }) => {
    btnEl.disabled = true // optional
    btnEl.dataset.toggled = 'true' // using the DOM to hold data

    if (btnEls.some(el => el.dataset.toggled !== 'true')) return

    msgEls.forEach(el => {
      el.textContent = 'Congratulations you clicked on all of the buttons'
    })
  }

  // Our "onclick" equivalent
  btnEls.forEach(el => el.addEventListener('click', handleButtonClick))
})()
<button class="js-button">Button1</button>
<button class="js-button">Button2</button>
<button class="js-button">Button3</button>
<button class="js-button">Button4</button>

<p class="js-message">Message displays here if all 4 buttons are clicked</p>

...可能有很多您不知道的语法,但该示例应该对那些从更现代的资源中学习的人有所帮助。由于您正在学习使用旧 JS 语法的东西,这里有一些旧 JS 代码的工作原理大致相同(但维护起来不那么容易):

// IIFE to keep variables out of the global scope
;(function () {
  // NOTE: These are more flexible when they are arrays (thus, Array.from())
  var btnEls = Array.from(document.querySelectorAll('.js-button'))
  var msgEls = Array.from(document.querySelectorAll('.js-message'))

  function handleButtonClick(event) {
    var btnEl = event.target
    btnEl.disabled = true // optional
    btnEl.dataset.toggled = 'true' // using the DOM to hold data

    if (btnEls.some(function (el) {
      return el.dataset.toggled !== 'true'
    })) return

    msgEls.forEach(function (el) {
      el.textContent = 'Congratulations you clicked on all of the buttons'
    })
  }

  // Our "onclick" equivalent
  btnEls.forEach(function (el) {
    el.addEventListener('click', handleButtonClick)
  })
})()
<button class="js-button">Button1</button>
<button class="js-button">Button2</button>
<button class="js-button">Button3</button>
<button class="js-button">Button4</button>

<p class="js-message">Message displays here if all 4 buttons are clicked</p>