如何声明变量只能在所有函数中使用“onclick”

时间:2017-09-27 20:54:26

标签: javascript

我想知道如何在函数之前只使用一次变量,这样我就可以使用变量而不必在每个函数中再次声明它们?

window.onload = function() {
    document.getElementById("soma").onclick = soma;
    document.getElementById("subtracao").onclick = subtracao;
    document.getElementById("multiplicacao").onclick = multiplicacao;
    document.getElementById("divicao").onclick = divicao;

    function soma() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 + n2);
    }

    function subtracao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 - n2);
    }

    function multiplicacao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 * n2);
    }

    function divicao() {
        var n1 = parseFloat(document.getElementById("n1").value);
        var n2 = parseFloat(document.getElementById("n2").value);
        document.getElementById("resultado").value = (n1 / n2);
    }
}

3 个答案:

答案 0 :(得分:1)

您可以在window.onload函数的顶部声明变量,如下所示:

window.onload = function() {
  var yourVariable;
}

您可以在任何功能(somasubtracaomultiplicacaodivicao)中使用此变量。

以下是一个例子:

window.onload = function() {
  var yourVariable = "Value";
  
  function testFunc() {
    console.log(yourVariable);
  }
  
  testFunc();
}

您可以在此处找到有关scopegloballocal变量的更多信息:https://www.w3schools.com/js/js_scope.asp

在这里:https://stackoverflow.com/a/500459/6053654

答案 1 :(得分:1)

n1个函数之外定义n2onclick变量:

window.onload = function() {
  document.getElementById("soma").onclick = soma;
  document.getElementById("subtracao").onclick = subtracao;
  document.getElementById("multiplicacao").onclick = multiplicacao;
  document.getElementById("divicao").onclick = divicao;

  var n1 = parseFloat(document.getElementById("n1").value);
  var n2 = parseFloat(document.getElementById("n2").value);

  function soma() {
    document.getElementById("resultado").value = (n1 + n2);
  }

  function subtracao() {
     document.getElementById("resultado").value = (n1 - n2);
  }

  function multiplicacao() {
    document.getElementById("resultado").value = (n1 * n2);
  }

  function divicao() {
    document.getElementById("resultado").value = (n1 / n2);
  }
}

现在您应该为n1n2听众提供更改:

document.getElementById("n1").onchange = n1Change;
document.getElementById("n2").onchange = n2Change;

function n1Change() {
  n1 = parseFloat(document.getElementById("n1").value);
}

function n2Change() {
  n2 = parseFloat(document.getElementById("n2").value);
}

答案 2 :(得分:0)

要使变量可用于所有函数,请在函数的封闭范围内声明它们 - 也就是说,在这种情况下,将它们声明在页面就绪(已加载)事件处理程序的顶部。

这个完整的演示包括我在对这个问题的评论中提到的建议;它使用DOMContentLoaded事件而不是onload,并且添加事件侦听器,其中.onload = ...onclick = ...盲目地分配事件处理程序,可能会替换现有的事件处理程序。

这是一个完整的.html文件,您可以将其保存并加载到浏览器中:

<!DOCTYPE html>
<html>
<head>
    <title>SO 46457061</title>
    <script>
    document.addEventListener('DOMContentLoaded', function(event) {

        // Get the two number and one answer elements once and store them,
        // saving us from having to traverse the DOM every time.
        // Declaring these here makes them available to all code within
        // this anonymous event-listener function.
        var n1el = document.getElementById('n1');
        var n2el = document.getElementById('n2');
        var resultEl = document.getElementById('result');

        // Attach a click-event handler to each of the buttons,
        // providing an anonymous function as the handler.
        document.getElementById('soma')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    // Log just to demonstrate
                    console.log('n1 = ' + n1.value);
                    console.log('n2 = ' + n2.value);
                    // Compute
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) +
                         parseFloat(n2.value));
                });

        document.getElementById('subtracao')
                .addEventListener('click', function(e) {
                    // Stop what normally happens on a button-click, and...
                    e.preventDefault();
                    // ...instead set the text of the answer to the computed value
                    // This performs the operation on the numbers, as numbers,
                    // but adds a string at the start to force the result to be
                    // a String. This is not strictly necessary, since assigning
                    // it to .innerText also converts to a String.
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) -
                         parseFloat(n2.value));
                });

        document.getElementById('multiplicacao')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) *
                         parseFloat(n2.value));
                });

        document.getElementById('divicao')
                .addEventListener('click', function(e) {
                    e.preventDefault();
                    resultEl.innerText = '' +
                        (parseFloat(n1.value) /
                         parseFloat(n2.value));
                });

    });
    </script>
    <style>
    button {
        height: 1.5em;
        width: 1.5em;
        font-size: 20px;
        margin-bottom: 5px;
    }
    section {
        display: inline-block;
    }
    </style>
</head>
<body>

    <section id="numbers">
        <label for="n1">First Number</label> <input type="text" id="n1" name="n1">  <br>
        <label for="n2">Second Number</label> <input type="text" id="n2" name="n2"> <br>
        <span class="result">Result: <span id="result">_</span></span>
    </section>

    <section id="operators">
        <button id="soma">&#x2b;</button>
        <button id="subtracao">&minus;</button>     <br>
        <button id="multiplicacao">&times;</button>
        <button id="divicao">&divide;</button>
    </section>

</body>
</html>

同样的事情,基本上,但作为一个堆栈片段,所以你可以在这里看到它。

document.addEventListener('DOMContentLoaded', function(event) {

    // Get the two number and one answer elements once and store them,
    // saving us from having to traverse the DOM every time.
    // Declaring these here makes them available to all code within
    // this anonymous function.
    var n1el = document.getElementById('n1');
    var n2el = document.getElementById('n2');
    var resultEl = document.getElementById('result');

    // Attach a click-event handler to each of the buttons,
    // providing an anonymous function as the handler.
    document.getElementById('soma')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) +
                    parseFloat(n2.value);
            });

    document.getElementById('subtracao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) -
                    parseFloat(n2.value);
            });

    document.getElementById('multiplicacao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) *
                    parseFloat(n2.value);
            });

    document.getElementById('divicao')
            .addEventListener('click', function(e) {
                e.preventDefault();
                resultEl.innerText =
                    parseFloat(n1.value) /
                    parseFloat(n2.value);
            });

});
button {
    height: 1.5em;
    width: 1.5em;
    font-size: 20px;
    margin-bottom: 5px;
}
section {
    display: inline-block;
}
<section id="numbers">
    <label for="n1">First Number</label> <input type="text" id="n1" name="n1">  <br>
    <label for="n2">Second Number</label> <input type="text" id="n2" name="n2"> <br>
    <span class="result">Result: <span id="result">_</span></span>
</section>

<section id="operators">
    <button id="soma">&#x2b;</button>
    <button id="subtracao">&minus;</button>     <br>
    <button id="multiplicacao">&times;</button>
    <button id="divicao">&divide;</button>
</section>