【问题标题】:Satisfying button click condition to bring up a message in javascript满足按钮单击条件以在javascript中显示消息
【发布时间】:2020-11-12 20:58:42
【问题描述】:

如果我的代码真的很糟糕,但我只是一个初学者,请提前道歉。我想使用按钮创建一个单词搜索谜题。当这个人通过单击我要从按钮中制作的所有单词完成查找时,我希望出现一条消息,表明他们已经完成了拼图。所以我在这里创建了一个带有 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>

【问题讨论】:

  • 当您关闭花括号时,您的函数会在您的第一个 value = true; 之后立即结束。您的 if 语句甚至不在函数中。我认为您想在括号 myFunction(value=true) {...} 内添加花括号中的语句。接下来,您需要定义p。并且可能使用== 来检查它的值:if (p == 1){...} 但是你也没有检查value 的任何东西,那么它的目的是什么?
  • 是的,我还有很多东西要学。谢谢你的解释。欣赏!

标签: javascript html boolean


【解决方案1】:

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

此外,像 onclick="myfunction()" 这样将 JS 内联对您的代码有些不利 - 它鼓励全局变量并使 JS 逻辑更难遵循。所以,我展示了一个使用IIFE.querySelectorAll().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>

【讨论】:

    【解决方案2】:

    这是我的解决方案。

    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>

    【讨论】:

    • 这样一个可爱的选择。谢谢!
    • 没问题 :) 但是,我认为您得到的答案不会超过 4 个,因此您应该将其中一个标记为正确(不一定是我,顺便说一句,我认为所有这些都是不错的选择)。
    【解决方案3】:

    一个更简单的方法是使用一个事件监听器来监听每个按钮的点击,然后将该按钮的值设为真,然后检查所有按钮是否都被点击,如果是则输出祝贺消息

    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";
      }
    })
    

    【讨论】:

    • 我喜欢这个。我需要将代码实现到我用来创建拼图的动画程序中。所以我认为你把它放在一起的方式对我有用,但需要一些时间来尝试。非常感谢!
    【解决方案4】:

    我建议这是一个更容易理解 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 值,这意味着有一个按钮没有被点击。当函数没有停止时,它将显示成功消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多