简体   繁体   English

您如何使用 HTML 按钮单击来调用 javascript function?

[英]How do you call a javascript function with a HTML button click?

So, I'm trying to make a dice roller that can, you guessed it,.所以,我正在尝试制作一个骰子滚轮,你猜对了。 roll dice.掷骰子。 I want to call a javascript function within a HTML button click, I know this is very easy with angular.我想在 HTML 按钮单击中调用 javascript function,我知道使用 ZD18B8624A0F5F72DDDFC7 很容易。 but I am not using Angular, I am using jQuery, but I don't want to make the whole thing jQuery, however, if I have to.但我没有使用 Angular,我使用的是 jQuery,但我不想制作整个 jQuery,但是,如果必须的话。 I will, Anyway, I am trying to make a button that adds a die, one that removes a die, one that adds a side to the dice.我会的,无论如何,我正在尝试制作一个添加骰子的按钮,一个移除骰子的按钮,一个为骰子添加一面的按钮。 and one that removes a side from the dice, Oh, and one that rolls the dice.还有一个是去掉骰子的一面,哦,还有一个是掷骰子的。 but I've already coded that in.但我已经把它编码进去了。
Here's my HTML (note: I am using jQuery so it might look a little weird):这是我的 HTML(注意:我使用的是 jQuery,所以看起来有点奇怪):

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      $("#button0").click(function(){
        diceRoll = 0
        for (i=diceAmt;i>0;i--) {
          diceRoll += rand(1, diceSides)
        }
        document.getElementById("dieRoll").innerHTML = diceRoll;
      })
    </script>
  </head>
  <body>
    <div class="screen">
      <div class="top">
        <div class="text">
          <span id="dieRoll"></span>
        </div>
        &nbsp;
        <button class="button1" id="button0"></button>
      </div>
      <div class="bottom">
        <button class="button2">Add die</button>
        &nbsp;
        <button class="button3">Remove die</button>
        <br/>
        <button class="button2">Add side</button>
        &nbsp;
        <button class="button3">Remove side</button>
      </div>
    </div>
  </body>
</html>

Here's my JavaScript (again might look a little weird):这是我的 JavaScript(可能看起来有点奇怪):

var diceAmt = 2
var diceSides = 6
var diceRoll
var xDx = diceAmt+"d"+diceSides
function floor(num){let n1=Math.round(num);let n2=n1-1;if(n1>num){return n2}else{return n1}}
function rand(num1,num2){let n1=num2+1-num1;let n2=floor(Math.random()*n1)+num2;return n2}
function addDie () {
  diceAmt += 1
  xDx = diceAmt+"d"+diceSides
  document.getElementById("button0").innerHTML = "Roll "+xDx
}
function rmoveDie () {
  diceAmt -= 1
  xDx = diceAmt+"d"+diceSides
  document.getElementById("button0").innerHTML = "Roll "+xDx
}
function addSide () {
  diceSides += 1
  xDx = diceAmt+"d"+diceSides
  document.getElementById("button0").innerHTML = "Roll "+xDx
}
function rmoveSide () {
  diceSides -= 1
  xDx = diceAmt+"d"+diceSides
  document.getElementById("button0").innerHTML = "Roll "+xDx
}

Now, I would normally show you my CSS here, but the CSS doesn't matter.现在,我通常会在这里向您展示我的 CSS,但 CSS 并不重要。
Oh, I almost forgot to show you the libraries I'm using.哦,我差点忘了向您展示我正在使用的库。 Here they are:他们来了:
jquery.js jquery.js

I would really like it if you could help me out here.如果你能在这里帮助我,我真的很喜欢。

Thank you!谢谢!

(Note: I would normally do that part in code but I figured it would be cooler if it was an actual h1.) (注意:我通常会在代码中执行该部分,但我认为如果它是实际的 h1 会更酷。)

Whenever a button is triggered a click event is fired.每当触发按钮时,就会触发单击event To handle that event there are 3 ways in vanilla javascript:要处理该事件,在 vanilla javascript 中有3种方法:

1. Specifying the function to be called in an HTML tag. 1. 在 HTML 标签中指定要调用的 function。

<button class="button2" onclick="addDie()">Add die</button>

2. Adding a handler in the button onclick property in JS. 2.在JS中的按钮onclick属性中添加处理程序。

const button = document.getElementById("your_button_id");
button.onclick = function(event) {
// do something
}
// or in your case
button.onclick = addDie

3. Adding an event listener 3.添加事件监听器

With this approach, you can add any number of handler for your event in the button.使用这种方法,您可以在按钮中为您的事件添加任意数量的处理程序。

button.addEventListener("click", addDie);
button.addEventListener("click", dieRoll);

These three are the possible ways to handle the events using vanilla JS.这三种是使用 vanilla JS 处理事件的可能方法。

Since you are using jquery you can simply do,由于您使用的是 jquery 您可以简单地做,

$("#button2").click(addDie)

To make sure the events are attached safely you would need to wait till the document is loaded.为确保安全地附加事件,您需要等到文档加载完毕。

1. In Jquery 1. 在 Jquery

$( document ).ready(function() {
...
$("#button2").click(addDie)
...
}

2. In Vanilla JS 2. 在香草 JS

document.addEventListener("DOMContentLoaded", function(){
...
 button.addEventListener("click", addDie);
 button.addEventListener("click", dieRoll);
...
});

Knowing the above three ways will help you understand the ways events can be handled with vanilla js.了解以上三种方式将帮助您了解使用 vanilla js 处理事件的方式。

Based on the code you showed, I think the issue is that your script is in the head part, before the body (including the buttons) is even loaded.根据您显示的代码,我认为问题在于您的脚本位于head ,甚至在加载正文(包括按钮)之前。

That means that when you do $("#button0") , you get a collection of zero elements (the buttons don't exist yet), and then you attach a click handler to zero elements, so you are doing nothing.这意味着当您执行$("#button0")时,您将获得零元素的集合(按钮尚不存在),然后将click处理程序附加到零元素,因此您什么也不做。

The solution is simple: jQuery allows you in a very simple way to defer the execution of some code until the DOM has finished loading.解决方案很简单:jQuery 允许您以一种非常简单的方式延迟某些代码的执行,直到 DOM 完成加载。 That is done by calling $ as a function and passing a callback, ie $(...) (or, more verbosely, by writing $(document).ready(...) ):这是通过将$称为 function 并传递回调来完成的,即$(...) (或者,更详细地,通过编写$(document).ready(...) ):

  $(function () {
      $("#button0").click(function(){
        diceRoll = 0
        for (i=diceAmt;i>0;i--) {
          diceRoll += rand(1, diceSides)
        }
        document.getElementById("dieRoll").innerHTML = diceRoll;
      })
  })

That should fix the issue.那应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM