无法从函数中访问全局变量

问题描述 投票:0回答:1

我正在尝试设置 numberTotal 作为一个全局变量,这样我就可以在全局变量之外访问它。cardNum_auto 函数。它是由表单输入字段中的onblur触发的,我需要访问它来填充底部的URL。我需要访问它来填充底部的URL。如果我把它全部放在函数中,它可以工作,但会创建多个按钮。

<div style="width: 100%; text-align: center; margin-top: 20px; margin-bottom: 20px;">
  <form id="golf-card-tally">
    <h3 style="margin-top: 20px; margin-bottom: 0px;">ORDER YOURS TODAY!!</h3>
    <div style="width: 400px; display: inline-block;">
      <div style="margin-bottom:10px">
        <div style="text-align:center">
          <h3>Enter Number of Cards</h3>
        </div>
        <div><input id="cardNum" type="number" onblur="cardNum_auto(this)" /></div>
      </div>
  </form>
</div>
<div id="golf-card-tally"></div>
var numberTotal;

function cardNum_auto(input) {
  numberTotal = input.value;
  console.log("numberTotal " + numberTotal + " in the function!");
}

console.log("numberTotal " + numberTotal + " out of the function!");

var golfCardDiv = document.createElement('div');
golfCardDiv.innerHTML = '<div style="width: 100%; text-align: center; margin-bottom: 20px;"><button style="border: 0px; border-radius: 18px;height:38px; width: 160px; color: white; font-weight: bold; background-color: #417505; cursor: pointer;"onclick="window.open(\'https://google.com?m=9272&amp;amount=' + numberTotal + '&amp;invoice=\')"type="submit">Submit Payment</button></div>';
var element = document.getElementById("golf-card-tally");
element.appendChild(golfCardDiv);

javascript variables global onblur
1个回答
0
投票

我看到的是每次输入失去焦点时,都会创建一个按钮。这是因为输入保持事件监听器。你应该在你的函数中删除事件监听器。cardNum_auto.要做到这一点,你不能打电话给 cardNum_auto 并在您的脚本中声明它。

在您的HTML

<div><input id="cardNum" type="number"/></div>

在JS中

var numberTotal;

function cardNum_auto() {
    input.removeEventListener('blur',cardNum_auto)
    numberTotal = input.value;
    var golfCardDiv = document.createElement('div');
    golfCardDiv.innerHTML = '<div style="width: 100%; text-align: center; margin-bottom: 20px;"><button style="border: 0px; border-radius: 18px;height:38px; width: 160px; color: white; font-weight: bold; background-color: #417505; cursor: pointer;"onclick="window.open(\'https://google.com?m=9272&amp;amount=' + numberTotal + '&amp;invoice=\')"type="submit">Submit Payment</button></div>';
    var element = document.getElementById("golf-card-tally");
    element.appendChild(golfCardDiv);
}

let input = document.querySelector('#cardNum')
input.addEventListener('blur',cardNum_auto)
© www.soinside.com 2019 - 2024. All rights reserved.