如何在每次点击按钮时执行 JavaScript 代码?

How to execute JavaScript code on every button click?

提问人:DSACRM 提问时间:11/16/2023 最后编辑:Peter SeligerDSACRM 更新时间:11/16/2023 访问量:85

问:

使用当前提供的下一个 HTML 标记,每次单击按钮时,页面都会重新加载。

<h1>Refresh Me</h1>
<div>
  <button onclick="window.location.reload()">
    Let's Find Out
  </button>
</div>

目标是,在单击按钮时,执行以下 JavaScript 代码。

var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomDiceImage = "dice" + randomNumber1 + ".png";
var randomImageSource = "images/" + randomDiceImage;
var image1 = document
  .querySelectorAll('img'[0]
  .setAttribute("src", randomImageSource);

var randomNumber2 = Math.floor(Math.random() * 6) + 1;
var randomDiceImage2 = "dice" + randomNumber2 + ".png";
var randomImageSource2 = "images/" + randomDiceImage2;
var image2 = document
  .querySelectorAll("img")[1]
  .setAttribute("src", randomImageSource2);

if (randomNumber1 > randomNumber2) {

  document.querySelector("h1").innerText = "Kirsty Makes Tea";

} else if (randomNumber1 < randomNumber2) {

  document.querySelector("h1").innerText= "Danny Makes Tea";

} else {
  document.querySelector("h1").innerText= "It's a draw";
}

如何实现这样的行为?

javascript 事件处理 dom-events

评论

0赞 Peter B 11/16/2023
你可以把所有的JS放在一个函数中,例如 然后放入事件处理程序。function rollDice() { -PUT JS CODE HERE- }rollDice()onClick=
0赞 DBS 11/16/2023
将希望它运行的代码放在函数中,然后调用该函数。或者更好的是,使用事件侦听器在 JS 中调用该函数,而不是使用 HTML 函数调用。
0赞 Peter Seliger 11/17/2023
@DSACRM......关于所有的答案,还有什么问题吗?
0赞 Peter Seliger 11/30/2023
@DSACRM......关于所有的答案,还有什么问题吗?

答:

0赞 Mister Jojo 11/16/2023 #1

在整个窗口上使用 Click 事件侦听器:

const
  [diceK, diceD] = [...document.querySelectorAll('.dice > span')]
, sentence       = document.querySelector('p')
, diceFace       = ['&#9856;','&#9857;','&#9858;','&#9859;','&#9860;','&#9861;']
, randomDice  =()=> Math.floor(Math.random()*6)
  ;
window.addEventListener('click', () =>  
  {
  let R1 = randomDice(), R2 = randomDice();
  diceK.innerHTML = diceFace[R1];
  diceD.innerHTML = diceFace[R2];
  
  if      (R1 < R2) sentence.textContent = 'Kirsty Makes Tea';
  else if (R1 > R2) sentence.textContent = 'Danny Makes Tea';
  else              sentence.textContent = 'Its a draw';
  });
html {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 16px;
  }
.dice {
  display     : inline-block;
  text-align  : center;
  padding     : 0;
  margin      : 0 0 0 1rem;
  caret-color : transparent;
  cursor      : default;
  }
.dice span {
  display     : inline-block;
  font-size   : 10rem;
  line-height : 8rem;
  height      : 8rem;
  background  : lightgreen;
  }
<div class="dice"> Kirsty<br><span>&#9856;</span></div>   
<div class="dice"> Danny <br><span>&#9861;</span></div>   
<p> click anywhere...</p>

0赞 Peter Seliger 11/16/2023 #2

OP 需要将处理掷骰子的代码放入函数中。然后,应该触发掷骰子的按钮必须订阅一个事件侦听器,其中函数被注册为处理程序'click'

然后,OP 的示例代码可能会更改为类似的东西......

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

function handleRollDice() {
  const [imageElement1, imageElement2] = Array
    .from(
      document.querySelectorAll('img')
    );
  const outputElement = document.querySelector('h1');

  const number1 = rollDice();
  const imageSource1 = "images/dice" + number1 + ".png";
  const imageAltText1 = "Kirsty's dice ... Number: " + number1;

  const number2 = rollDice();
  const imageSource2 = "images/dice" + number1 + ".png";
  const imageAltText2 = "Danny's dice ... Number: " + number2;

  imageElement1.src = imageSource1;
  imageElement1.alt = imageAltText1;

  imageElement2.src = imageSource2;
  imageElement2.alt = imageAltText2;

  if (number1 > number2) {

    outputElement.innerText = 'Kirsty makes tea';

  } else if (number1 < number2) {

    outputElement.innerText = 'Danny makes tea';

  } else {
    outputElement.innerText = "It's a draw";
  }
}
document
  .querySelector('.roll-dice > button')
  .addEventListener('click', handleRollDice);
body { margin: 0; }
.roll-dice { margin: 20px 0; }
img { margin: 0 20px; }
<h1>Roll Dice</h1>

<img src="images/dice4.png" alt="Kirsty's dice ... Number: 4"/>
<img src="images/dice4.png" alt="Danny's dice ... Number: 4"/>

<div class="roll-dice">
  <button>Roll Dice</button>
</div>

OP 的代码稍后可以使用其他一些技术/方法,例如

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

function rollDiceFor(root) {
  const [playerRoot1, playerRoot2] = [...root.querySelectorAll('.player')];

  const name1 = playerRoot1.dataset.name;
  const name2 = playerRoot2.dataset.name;

  const dice1 = playerRoot1.querySelector('.dice');
  const dice2 = playerRoot2.querySelector('.dice');

  const diceFace1 = rollDice();
  const diceFace2 = rollDice();

  dice1.dataset.face = diceFace1;
  dice2.dataset.face = diceFace2;

  const output = root.querySelector('output');
  const outputData = output.dataset;

  output.value =  (
    ((diceFace1 === diceFace2) && outputData.draw) ||
    `${ (diceFace1 < diceFace2) && name1 || name2 } ${ outputData.task }`
  );
}

function handleRollDice(evt) {
  rollDiceFor(
    evt.currentTarget.closest('.roll-dice')
  );
}
document
  .querySelector('.roll-dice > button')
  .addEventListener('click', handleRollDice);
body { margin: 0; }

.roll-dice {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.game {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.player {
  margin: 5px 20px;
}
.dice {
  margin-top: 10px;
}
output {
  display: block;
  min-height: 1.2em;
  margin: 15px 0;
}
.dice[data-face="1"] {
  background-position: -4px -4px!important;
}
.dice[data-face="2"] {
  background-position: -96px -4px!important;
}
.dice[data-face="3"] {
  background-position: -188px -4px!important;
}
.dice[data-face="4"] {
  background-position: -5px -95px!important;
}
.dice[data-face="5"] {
  background-position: -98px -95px!important;
}
.dice[data-face="6"] {
  background-position: -189px -97px!important;
}
.dice[data-face] {
  width: 82px;
  height: 82px;
  background-position: 80px 80px;
  background-repeat: no-repeat;
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAAC3CAMAAAAGjUrGAAAA/FBMVEX/////ZmYAAAD/aWno6Oju7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Di285KAx/vWOVo4IvG8YD+5n22Ru6av662EvKX2nuvD1bj55Zb8dlXdzQE9N1cc7bunhEKQx/XYx7XS/82R3PNFVXcZ94wASPa3H+/tJuv/3ybj8pTw/nt35hdotjLMA9jGuR7w1b7fYv7/aTpqMw20z7yfixNS0HaT5iPPO82SFVY7gd8U9I+xNXNGjHyrjFPwlrZ8MyZhx8I+4VZ2eTUoeSSIHRgkRnh8DanejQKnjikLTI2PnTaEE4haSo4GwLOUxZP+4IjV4FOSRFRgszSg3DM+0LjWYTx4DHQmZWIeUH3j9diFR+QYQEVEVmh9hCKey3Q4Gap7pBv/qKxKQqkKYvkswFERcX/k19BQEH06IiMs7kADZo41li4kypu47QhtPvPiOmw4oiIrDZF4HfZdyB4Ac6vIxux0LJdn2/T41rFkfoRz2k8lg0ferIPBFBh6ICVcbBVzmX7ZSAAK/9A3qDUC9FRKc9de7hRhDaETH4RH5QkBiSjG2HlCOX4h2FVR6jtojkAUKpg91wcnyKRO+ZL1ciF6/9kA1wLxX/qxGMN7KRjayJ/A/wuTyUx9WEsAAAAABJRU5ErkJggg==);
}
<section class="roll-dice">

  <div class="game">
    <div class="player" data-name="Kirsty">

      <em>Kirsty's dice ...</em>
      <div class="dice" data-face="5"></div>

    </div>
    <div class="player" data-name="Danny">

      <em>Danny's dice ...</em>
      <div class="dice" data-face="5"></div>

    </div>
  </div>

  <output data-task="makes tea" data-draw="It's a draw"></output>

  <button>Roll dice ...</button>

</section>

0赞 stan 11/16/2023 #3

您可以通过将所有 javascript 添加到单个函数中来做到这一点。

JavaScript的

function randomDice() {
  var randomNumber1 = Math.floor(Math.random()*6)+1;
        var randomDiceImage = "dice"+randomNumber1+".png";
        var randomImageSource = "images/"+randomDiceImage;
        var image1 = document.querySelectorAll('img')[0].setAttribute("src",randomImageSource);
        
        var randomNumber2 = Math.floor(Math.random()*6)+1;
        var randomDiceImage2 = "dice"+randomNumber2+".png";
        var randomImageSource2 = "images/"+randomDiceImage2;
        var image2 = document.querySelectorAll("img")[1].setAttribute("src",randomImageSource2);
             
        
        if(randomNumber1 > randomNumber2){
        document.querySelector("h1").innerText = "Kirsty Makes Tea";
        }
        else if(randomNumber1 < randomNumber2){
        document.querySelector("h1").innerText= "Danny Makes Tea";
        }else{
            document.querySelector("h1").innerText= "Its a draw";
        }
}

然后在你的html中使用这个函数:

<h1>Refresh Me</h1>
  <div>
     <button onclick="randomDice()" type="button" class="button">Let's Find Out</button>
  </div>