将提示值传递给"触发的功能;点击"输入按钮上的事件

时间:2017-03-01 12:08:16

标签: javascript button input onclick click

我有一个代码,用于创建3个按钮(使用JavaScript),并在每个按钮上添加我为点击事件添加事件监听器 。所有按钮在点击时都会执行相同的功能,这是 mathProb() [我知道它没有多大意义,但我只是想试验一下与事物]

mathProb()函数需要3个参数:

  1. firstNumber ,这是第一个操作数。

  2. secondNumber 这是第二个操作数

  3. operationSign 这是两个操作数之间要执行的操作

  4. 这里是 mathProb 函数(我把函数放在HTML头元素中):

    function mathProb(firstNumber, secondNumber, operationSign){
            switch(operationSign){
                case "+":
                    var sum = (firstNumber + secondNumber).toFixed(2);
                    document.writeln("The sum of [" + firstNumber + " + " + secondNumber + "] is " + sum + " (adjusted to 2 decimal places)");
                    break;
    
                case "-":
                    var subtract = (firstNumber - secondNumber).toFixed(2);
                    document.writeln("The subtraction of [" + firstNumber + " - " + secondNumber + "] is " + subtract + " (adjusted to 2 decimal places)");
                    break;
    
                case "*":
                    var multiplication = (firstNumber * secondNumber).toFixed(2);
                    document.writeln("The multiplication of [" + firstNumber + " X " + secondNumber + "] is " + multiplication + " (adjusted to 2 decimal places)");
                    break;
    
                case "/":
                    var division = (firstNumber / secondNumber).toFixed(2);
                    document.writeln("[" + firstNumber + " divided by " + secondNumber + "] is " + division + " (adjusted to 2 decimal places)");
                    break;
    
                default:
                    document.writeln("You did not specify the operation sign, no operation could be performed between the two numbers!");
            }
        }
    

    现在我计划使用 prompt()方法获取函数将使用的3个参数,因此我在body元素中放入的JavaScript代码如下所示:

        //create all the mathematical buttons
        var addButton = document.createElement("input");
        var subtractButton = document.createElement("input");
        var multiplyButton = document.createElement("input");
        var divideButton = document.createElement("input");
        addButton.type = "button";
        subtractButton.type = "button";
        multiplyButton.type = "button";
        divideButton.type = "button";
    
        var firstNumber = parseFloat(prompt("Please enter the first number"));
        var secondNumber = parseFloat(prompt("Please enter the second number"));
        var operationSign = prompt("Please enter the operation sign you wish to perform on the two numbers");
    
    
        //add a click event listener to all of the buttons
        addButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
        subtractButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
        multiplyButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
        divideButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
    
        //add all the buttons to the body of the document
        document.body.appendChild(addButton);
        document.body.appendChild(subtractButton);
        document.body.appendChild(multiplyButton);
        document.body.appendChild(divideButton);
    

    我意识到我还没有添加任何"价值"按钮,所以我现在无法区分它们

    我的问题是,一旦我运行我的代码,我得到了3个提示,它们会询问我 firstNumber secondNumber operationSign 。但是,出于某种原因,似乎 mathProb() 功能被执行4次没有我点击任何按钮

    以下我将 2 作为firstNumber 3 时发生了什么 作为secondNumber + 作为operationSign

    http://imgur.com/a/APFbf

    看看我在说什么?我不知道这里发生了什么,我似乎也无法弄清楚代码的错误(我在javascript / html / css方面非常缺乏经验)。

2 个答案:

答案 0 :(得分:1)

.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));

应该是这样的:

.addEventListener("click", function(evt) { 
mathProb(firstNumber,secondNumber,operationSign);
});

如果要将函数传递给参数(不执行),请使用functionName without()。

示例:

var someFunctionWithFunctionInArgument = function(fun) {
  fun(1);
};

var superFunction = function(num) {
 alert(num);
};

someFunctionWithFunctionInArgument(superFunction); // alert 1

someFunctionWithFunctionInArgument(superFunction(2)); // alert 2 and error becouse fun is not a function now

答案 1 :(得分:0)

你太复杂了 你可以有这个简单的解决方案

function operate(val1,op,val2){
  switch(op){
    case '+' : return val1+val2; break;
    case '-' : return val1-val2; break;
    case '*' : return val1*val2; break;
    case '/' : return val1/val2; break;
    default : return 0; break;
  }
}
var start = document.createElement('button');
start.innerHTML="START";
start.addEventListener('click',function(){
  var result=operate(parseInt(prompt("first val")),prompt("Operator"),parseInt(prompt("Second val")));
  console.log(result);
});
document.body.appendChild(start);
<body></body>

甚至更简单

var button = document.createElement('button');
button.innerHTML="START";
button.addEventListener('click',function(){
  var val1=parseInt(prompt("First Val"));
  var op=prompt("Operator");
  var val2=parseInt(prompt("Second Val"));
  console.log(eval(val1+op+val2));
});
document.body.appendChild(button);
<body></body>

更简单

function start(){
  console.log(eval(prompt("Enter expression : "))); // like 10+5
}
function startWithTest(){
  var exp=prompt("Enter expression : ");
  if(/^\d+[+-\/*]{1}\d+$/.test(exp)){
    console.log(eval(exp));
  }
}
<body><button onclick="start();">START</button>&ensp;With validating :&ensp;<button onclick="startWithTest();">START With Test</button></body>