如何根据输入的值进行打印

时间:2017-09-18 23:24:35

标签: javascript

所以如果我输入10,那么10号应该打印10次



function function_name(number) {
  for (var counter = 1; counter <= number; counter++) {
    document.write("the number is" + number);
  }
}
&#13;
<label for="number">Enter number: </label>
<input name="number" id="number" />
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

看起来你只需要:

  • 向HTML添加按钮
  • 在您的按钮上添加一个点击处理程序,以激活您的功能

function writeTimes(number) {
  for (var counter = 1; counter <= number; counter++) {
    document.write("the number is" + number);
  }
}

function doTheThing() {
   var input = document.getElementById("my-input"); //get the input element
   var numberOfTimes = input.value; //get the number of times
   writeTimes( numberOfTimes  ); //call your function
}
<label for="number">Enter number: </label>
<input id="my-input" name="number" id="number" />
<button onclick="doTheThing()">Go</button>

答案 1 :(得分:0)

// This function *does* something. Give it a name that reflects it's behavior.
// You can always rename it later if you change what it does.
// 
function spamNumber(number) {

  // Use let instead of var, it's replacement for var with less wtf behavior
  //
  for (let counter = 1; counter <= number; counter++) {

    // I don't care for document.write. It's totally unusable in production code.
    // But sure, why not? At least add a line break so the outputs
    // don't smush together.
    //
    document.write("the number is " + number + '<br/>'); 
  }
}

// Find the input element so we can add a listener
//
document.querySelector('input')

  // Listening in this case only to keydowns that occur while input has focus.
  //
  .addEventListener('keydown', function onKeydown(evt) {

    if (event.key === 'Enter') {

      // evt.target is the input element, number in it's value property.
      // Force value to integer in case someone inputs garbage. We can
      // fail silently and move on.
      //
      spamNumber( parseInt(evt.target.value) || 0)
    }
  })

// Now type in your number and press Enter
 
 
<label for="number">Enter number: </label>
<input name="number" id="number" />

答案 2 :(得分:0)

从您的问题和评论中,我认为您正在寻找:

&#13;
&#13;
onload =  function (){
  var     result = document.getElementById('result');
  var     number = document.getElementById('number');
          number.oninput = function (){
   if(number.value == "0" || number.value.length == ""){result.innerHTML="";}else{} 
 var counter = "";
 var repeat =number.value;
     while (repeat > 0)         {
           repeat--;
  var str ="  (the number is  " + parseInt(number.value)+" )";
 result.innerHTML= str.repeat(number.value);
                                 }
          return counter;     

     number.onpropertychange = number.oninput; 
     number.onchange = number.oninput;
      }};
&#13;
<label for="number">Enter number: </label>
<input name="number" id="number" /><br />
<span id=result></span>
&#13;
&#13;
&#13;