首页 > 解决方案 > 在JS中使用按钮点击制作变量

问题描述

我有五个可能的按钮可以按下,每个按钮都运行相同的功能。但我也希望那个按钮也能创建一个独特的全局变量。一个变量,上面写着“这个按钮被按下了,所以在需要的地方添加这个”词。

document.getElementById("One").addEventListener("click", Variables);
document.getElementById("Two").addEventListener("click", Variables);
document.getElementById("Three").addEventListener("click", Variables);
document.getElementById("Four").addEventListener("click", Variables);
document.getElementById("Five").addEventListener("click", Variables);

所以它们都运行完全相同的函数,但“一”或“二”或“三”字符串需要成为一个全局变量。我后来用这些来做一些数字:

例如,我会使用“One”来产生以下结果之一:

if (mapNumber = "One" || "Three" || "Four") { 
    climate = ["dry", "light rain", "medium rain", "heavy rain", "light snow", "medium snow", "heavy snow", "light ice", "very icy", "severe ice"];

我对如何将其称为全球性感到有些茫然。我尝试在函数内部创建一个函数,但它似乎导致另一个函数停止。所以我猜我在某处犯了语法错误。

我尝试做一个onclick="myFunction(this.id)"函数以及 EventListener 但这似乎也不起作用。

指向正确方向的指针肯定会有所帮助。我已经进行了搜索,但这些似乎充其量只能产生局部变量。

谢谢 :)

标签: javascripthtmlvariablesonclickaddeventlistener

解决方案


你可以这样做:

  1. 为您的按钮添加一个带有类或 id 的容器,以便我们可以轻松地选择它们
  2. querySelectorAll获取所有按钮和...
  3. ...循环使用forEach并添加您的事件处理程序以进行点击
// Get all buttons
const mybuttons = document.querySelectorAll('.mybuttons button');

// loop through the buttons and add the event listener to each button
mybuttons.forEach(mybutton => {
   mybutton.addEventListener('click', processClick);
});
  1. 创建一个全局变量mapNumber以保存单击按钮的 id
    更新:注意 - 您需要使用var而不是let这样可以使用window.variablename
  2. 创建一个函数来处理点击,我们可以获取 id 来告诉我们点击了哪个按钮并将其用于mapNumber
var mapNumber;
function processClick() {
    mapNumber= this.id;  // the id of the clicked button 
}

工作示例:

var mapNumber;  
var climate;

//get all buttons in the mybuttons container
const mybuttons = document.querySelectorAll('.mybuttons button');

// add the event listener to each button
mybuttons.forEach(mybutton => {
     mybutton.addEventListener('click', processClick);
});

function processClick() {
    // save the id of the clicked button as mapNumber
    window.mapNumber = this.id;

    // set climate variable based on which was clicked, e.g.        
    switch(window.mapNumber){
        case "One":
        case "Three":
        case "Four":
            climate = ["dry", "light rain", "medium rain", "heavy rain", "light snow", "medium snow", "heavy snow", "light ice", "very icy", "severe ice"];
            break;
        case "Two":  climate = ["Two's climate"]; break;
        case "Five": climate = ["Five's climate"]; break;
    }

    // Display the mapNumber, just to show its working :)
    document.getElementById('mapNumber').innerHTML = "mapNumber: "+window.mapNumber;
    document.getElementById('climate').innerHTML = "Climate: "+climate;
}
<div class="mybuttons">
  <button id="One">One</button>
  <button id="Two">Two</button>
  <button id="Three">Three</button>
  <button id="Four">Four</button>
  <button id="Five">Five</button>
</div>
<div id="mapNumber">mapNumber:</div>
<div id="climate">Climate:</div>


推荐阅读