函数add()数字与提示

时间:2018-03-25 00:15:59

标签: javascript function add prompt

我想使用提示

简单地添加数字代码



function myFunction() {
  var x = prompt("");
  var add = (function () {
    var counter = 0;
    return function () {return counter += x;}
  })();
  document.getElementById("demo").innerHTML = add();
}

<button onclick="myFunction()">+</button>
<p id="demo"></p>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

我从IIFE中定义了函数,因此counter不会污染全局范围 - 然后,只返回函数,不需要任何更复杂的事情

const myFunction = (() => {
  let counter = 0;
  return () => {
    counter += Number(prompt('Number?'));
    document.getElementById("demo").innerHTML = counter;
  };
})();
<button onclick="myFunction()">+</button>
<p id="demo"></p>

答案 1 :(得分:1)

您的代码比需要的更复杂。不需要嵌套函数来进行数学运算。您还必须将用户提供的数据转换为数字(这可以通过在数据前加+来完成)。

此外,您的代码并未遵循最佳做法和标准。

请参阅以下代码中的评论。

// Get references to the HTML elements you'll use in JavaScript
var btn = document.getElementById("btn");
var output = document.getElementById("demo");
var counter = 0; // Running total will be here

// Set up event handling in JavaScript, not HTML
btn.addEventListener("click", function() {
  counter += +prompt("What is the number to add?"); // Convert response to number and add to counter
  output.textContent = counter; // Place result back into the document (use .textContent, not .innerHTML)
});
<button id="btn">+</button>
<p id="demo">0</p>

答案 2 :(得分:0)

  • 主要问题是在每次点击活动中都创建了函数add
  • 只需将其放在函数myFunction
  • 之外
  • 您需要将输入的值转换为数字,即使用运算符+

var add = (function() {
  var counter = 0;
  return function(x) {
    return counter += +x;
  }
})();

function myFunction() {
  var x = prompt("");
  document.getElementById("demo").innerHTML = add(x);
}
<button onclick="myFunction()">+</button>
<p id="demo"></p>

<强>建议:

使用 addEventListener 功能绑定事件click

// This is to illustrate the usage of 'addEventListener'.
// The function getElementsByTagName gets the whole set of elements button.
// In your case it doesn't make sense because you have only one.
// Like I said, this is just to illustrate.
var buttons = document.getElementsByTagName('button');
for (var btn of buttons) btn.addEventListener('click', myFunction);

//-----------

var add = (function() {
  var counter = 0;
  return function(x) {
    return counter += +x /*Convert to number*/;
  }
})();

function myFunction() {
  var x = prompt("");
  document.getElementById("demo").textContent = add(x);
}
<button>+</button>
<p id="demo"></p>