简体   繁体   English

从两个按钮组合HTML onclick函数?

[英]Combining HTML onclick functions from two buttons?

I am coding a choose your own adventure game, and I currently have two buttons on the page: one that passes variables from HTML to JavaScript, and one that calls the JavaScript function to start the game. 我正在编写一个自己选择的冒险游戏,目前页面上有两个按钮:一个将变量从HTML传递到JavaScript,另一个调用JavaScript函数启动游戏。 They both work fine on their own, but I want to merge them into one button that performs both functions. 它们都可以正常工作,但是我想将它们合并为一个同时执行这两个功能的按钮。 Here's the code: 这是代码:

  <button onclick="add(document.getElementById('FirstName').value, document.getElementById('LastName').value)">Add</button>

   <button onclick="pirates();"> Ready to Play? </button>   

Why not just add add(document.getElementById('FirstName').value, document.getElementById('LastName').value) To the beginning of your pirates() function, then clicking the 'Ready to Play?' 为什么不将add(document.getElementById('FirstName').value, document.getElementById('LastName').value)pirates()函数的开头,然后单击“准备播放”? button would do both things. 按钮会做两件事。

<script>
  function pirates(){
    add(
      document.getElementById('FirstName').value,
      document.getElementById('LastName').value
    )
  }
</script>
<button onclick="pirates();"> Ready to Play? </button> 

Assuming you add the id btn to your button, this script will get the values and pass them to pirates() . 假设将id btn添加到按钮,此脚本将获取值并将其传递给pirates()

var firstName;
var lastName

btn = document.getElementById('btn');

btn.onclick = function() {
  firstName = document.getElementById('FirstName').value;
  lastName = document.getElementById('LastName').value;
  pirates(firstName, lastName);
};

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

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