【问题标题】:Why text is not showing correct when the value matches为什么值匹配时文本显示不正确
【发布时间】:2021-09-28 21:24:54
【问题描述】:

我最近在0 和1 之间生成数字,它与两个btn 之一匹配的index 将被视为幸运并将color 更改为green 否则color 更改到red 和文字将显示其他是幸运的。

一切正常,但文本仅适用于 1 btn,即它会显示正确的文本,因为我很幸运,但对于其他 btn 没有正确意义

点击第一个btn可以看到:正确时,即绿色文字应该是“我很幸运”,但它显示“其他btn很幸运”

var btnLuck = document.getElementsByTagName("BUTTON");

function randomNumber()
  {
  var randNum = Math.floor(Math.random() * 2);
  document.getElementById("demo").innerHTML = randNum;

console.log('randNum =',randNum ) // ------------------

  for (let i = 0; i < btnLuck.length; i++)
    {
console.log('loop i value-- >', i )  // ------------------
    if (i == randNum)
      {
console.log('(i == randNum) is true')  // ------------------
      document.getElementById("demo").innerHTML = "You are lucky (" + randNum + ")";
      btnLuck[i].style.backgroundColor = "green"
      }
    else 
      {
console.log('(i == randNum) is false') // ------------------
      document.getElementById("demo").innerHTML = "Other btn is lucky (" + randNum + ")";
      btnLuck[i].style.backgroundColor = "red"
  } } }
<button onclick="randomNumber()">Lucky number 0</button>
<button onclick="randomNumber()">Lucky number 1</button>
<div id="demo"></div>

【问题讨论】:

  • 我在您的代码中添加了一些 console.log() 用于显示执行步骤——您可以使用这种旧技术来调试您自己的代码
  • 在你的脑海中跟踪脚本的执行,或者使用浏览器的调试器,你会看到发生了什么。
  • 这能回答你的问题吗? For loop only outputs last iteration

标签: javascript html


【解决方案1】:

我想你正在寻找类似的东西?

const
  demo_El  = document.querySelector('#demo')
, buttons  = document.querySelectorAll('button.forRandom') // first is°0 !
, replayBt = document.querySelector('#replay-button')

buttons.forEach( (btn,indexButton) =>
  {
  btn.textContent = `Lucky number ${indexButton +1}` // zero is blown by the wind 
  
  btn.onclick =_=> randomNumberTesting( btn,indexButton )
  })
replayBt.onclick =_=>
  {
  buttons.forEach(bt=>
    {
    bt.classList.remove('win', 'lost')
    bt.disabled = false
    })
  demo_El.textContent = '...?...'
  replayBt.disabled   = true
  }

function randomNumberTesting ( buttonElement, indexButton )
  {
  let randNum = Math.floor(Math.random() *buttons.length) // [0...,n-1]

  buttons.forEach(bt=> bt.disabled = true )

  if (randNum===indexButton)
    {
    demo_El.textContent = `You are lucky (${randNum +1})`
    buttonElement.classList.add('win')
    }
  else
    {
    demo_El.textContent = `"Other btn is lucky (${randNum +1})`
    buttonElement.classList.add('lost')
    buttons[randNum].classList.add('win')
    }
  replayBt.disabled = false
  }
.win  { background: lightgreen; }
.lost { background: lightcoral; }
<button class="forRandom"></button>
<button class="forRandom"></button>
<button class="forRandom"></button>
<button class="forRandom"></button> <!-- or more... -->


<p id="demo">...?...</p>

<button id="replay-button" disabled>replay</button>

【讨论】:

  • 感谢它真的很有帮助,解决了我的问题并提供了新的见解。但是你能告诉我为什么我的代码运行不正确
  • @Rana 因为你在每个按钮上继续循环 if 或 else 并重写你的 demo_El 文本的 2 倍
【解决方案2】:

我观察到您描述的问题,如果您愿意接受其他解决方案,那么我希望以下内容可能会引起您的兴趣。

/*
    Find the DOM elements of interest ~ one is a nodelist
*/
const demo=document.getElementById('demo');
const col=document.querySelectorAll('button');

/*
    assign an event handler to each button found and keep track of the
    buttons DOM nodelist index `i` as we will use that as a comparison
    to the random number generated.
*/
col.forEach((bttn,i)=>bttn.addEventListener('click',function(e){
    // create the random number
  let randNum = Math.floor( Math.random() * 2 );
  
    // output
    let who;
      
    // find the nodelist index of the `other` button
  let index=( ( 1 - i ) + 1 );
      
    // find the `other` node
  let other=this.parentNode.querySelector('button:nth-of-type('+index+')');
  
    // reset styles for both buttons
  col.forEach(bttn=>bttn.classList.remove('red','green'));
  
  /*
    so if the random number equals the clicked button's nodelist index
    then assign the class and change the class of the `other` element
  */
  if( i===randNum ){
    this.classList.add('green');
    other.classList.add('red');
    who='You are lucky ('+randNum+')';
  }else{
    this.classList.add('red');
    other.classList.add('green');
    who='Other btn is lucky ('+randNum+')';
  }

  demo.innerText=who;
}));
.red{background:red}
.green{background:green}
button:before{content:'Lucky Number - '}
<button>0</button>
<button>1</button>
<div id="demo"></div>

【讨论】:

  • 感谢它真的很有帮助,解决了我的问题并提供了新的见解。但是你能告诉我为什么我的代码运行不正确
猜你喜欢
  • 2011-08-14
  • 2014-03-23
  • 2017-08-05
  • 2013-05-19
  • 1970-01-01
  • 2022-07-16
  • 2021-05-30
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多