简体   繁体   English

JavaScript计算器-如何将数字输入字段?

[英]JavaScript Calculator - How to get numbers into input field?

So I have assigned all my numbers a class of numbers and all my operators a class of operators with ids specific to their operation. 因此,我为所有数字分配了一个数字类,并且为我的所有运算符分配了一个特定于其操作的ID的运算符类。 Every item is within a div tag. 每个项目都在div标签内。

Full data here: jsfiddle 完整数据在这里: jsfiddle

    <div class="number clear" id="clear"><h1>C</h1></div>
    <div class="number" id="entry"><input type="number"></div>
    <div class="number seven"><h1>7</h1></div>
    <div class="number eight"><h1>8</h1></div>
    <div class="number nine"><h1>9</h1></div>
    <div class="operate divide" id="divide"><h1>/</h1></div>

So the above is just a glimpse of the HTML. 因此,以上只是HTML的一瞥。 My CSS works perfectly fine but I'm struggling with the JavaScript. 我的CSS可以正常工作,但是我在JavaScript方面苦苦挣扎。 I've put in a for loop to pull from all the numbers in the HTML to do an addEventListener for onclick. 我放入了一个for循环,以从HTML中的所有数字中提取出内容来为onclick做一个addEventListener。 I feel confident in the for loop but I could definitely be wrong. 我对for循环充满信心,但我肯定是错的。 Right now I have the following: 现在,我有以下内容:

let number = document.getElementsByClassName("number");
let operate = document.getElementsByClassName("operate");
let entry = document.getElementById("entry");
let clear = document.getElementById("clear");
let sub=document.getElementById("sub");
let multiply = document.getElementById("mul");
let divide = document.getElementById("divide");
let add = document.getElementById("plus");

for (let i=0; i<numbers.length; i++) {
  numbers[i].addEventListener("click", function(entry)){
    let inputValue = entry[0].innerHTML;
    let buttonValue = this.html;
    if (buttonValue === "C") {
     entry[0].innerHTML = "";
    } else {
      entry[0].innerHTML += buttonValue;
    }
  }
}

function (entry){

}

I know I need to run a function in the for loop but for the life of me I'm drawing blanks as to what to enter to push the values from the div into the entry field for the calculation. 我知道我需要在for循环中运行一个函数,但是为了我的生命,我在绘制空白内容时将输入值从div推入输入字段进行计算。 Right now if I click on any of the buttons nothing happens, clearly as there's no function. 现在,如果我单击任何按钮,则不会发生任何事情,因为没有任何功能。 Any insight on how to adjust this to get something to populate would be appreciated. 任何有关如何调整它以填充某些东西的见解将不胜感激。

 let numbers = document.getElementsByClassName("number"); let entry = document.getElementById("entry"); for (let i=0; i<numbers.length; i++) { numbers[i].addEventListener("click", function(){ let buttonValue = this.textContent; if (buttonValue === "C") { entry.innerHTML = "0000"; } else { entry.innerHTML = (entry.innerHTML+buttonValue).substr(-4); } }); } 
 .number { display:inline-table; } 
 <h1><div id="entry">0000</div></h1> <div class="number"><h1>1</h1></div> <div class="number"><h1>2</h1></div> <div class="number"><h1>3</h1></div><br> <div class="number"><h1>4</h1></div> <div class="number"><h1>5</h1></div> <div class="number"><h1>6</h1></div><br> <div class="number"><h1>7</h1></div> <div class="number"><h1>8</h1></div> <div class="number"><h1>9</h1></div><br> <div class="number "><h1>C</h1></div> 

You just mixed up some variable names and used non existent properties... 您只是混合了一些变量名并使用了不存在的属性...

There are several issues in your code: 您的代码中存在几个问题:

  1. Your event listener accepts a parameter called entry , which overwrites the entry variable in the outer scope. 您的事件侦听器接受一个名为entry的参数,该参数将覆盖外部作用域中的entry变量。 The first parameter of the event listener that you pass to addEventListener contains information about the click event (which you normally don't need). 传递给addEventListener的事件侦听器的第一个参数包含有关click事件的信息(通常不需要)。 So remove the entry parameter from the event listener. 因此,从事件侦听器中删除entry参数。

  2. The value of this in an event listener is a reference to the element that you bound the event listener to. 事件侦听器中this的值是对您将事件侦听器绑定到的元素的引用。 It won't have a property called html . 它没有名为html的属性。

  3. You declare a variable called number , but use a variable called numbers . 您声明了一个名为number的变量,但使用了一个名为numbers的变量。

  4. numbers[i].addEventListener("click", function(entry)){ results in a syntax error. numbers[i].addEventListener("click", function(entry)){导致语法错误。 Remove the second ) between parameter list and the function body. 删除参数列表和函数主体之间的第二个)

  5. function (entry){} results in a syntax error, because function statements require a name. function (entry){}导致语法错误,因为函数语句需要名称。 Just remove it, it's superfluous. 只要删除它,它是多余的。

That said, get some inspiration from the following code snippet: 就是说,从以下代码片段中获得一些启发:

 const input = document.querySelector('input'); document.querySelectorAll('.number').forEach(function (button, index) { button.addEventListener('click', function () { input.value += index + 1; }); }); 
 <input type="number"> <button class="number">1</button> <button class="number">2</button> <button class="number">3</button> <button class="number">4</button> 

As mentioned by Jonas in his answer, there are a bunch of issues in your current code - including some syntax issues. 正如乔纳斯(Jonas)在回答中提到的那样,您当前的代码中存在很多问题-包括一些语法问题。 So I decided replace your event handler completely, and write it using jQuery - as it really comes in handy in such cases. 因此,我决定完全替换您的事件处理程序,并使用jQuery编写它-因为在这种情况下确实很方便。

The event handler looks like this: 事件处理程序如下所示:

$(".number").on("click", function(event){
    var num = $(this).text();
  console.log(num);

  if(num != 'C') {
    var currentNumber = $("#entryNum").val();
    $("#entryNum").val(currentNumber.toString() + num.toString());
  } else {
    $("#entryNum").val('');
  }
});

The logic of the event handler remains quite similar to your original logic, but I have just simplified it using jQuery. 事件处理程序的逻辑仍然与您的原始逻辑非常相似,但是我只是使用jQuery对其进行了简化。 Also, to allow for faster access to the input element, I gave it an ID entryNum : 另外,为了允许更快地访问输入元素,我给了它一个ID entryNum

<div class="number" id="entry"><input type="number" id="entryNum"></div>

Here's the updated fiddle: https://jsfiddle.net/Nisarg0/L9mL4v3a/6/ 这是更新的小提琴: https : //jsfiddle.net/Nisarg0/L9mL4v3a/6/

Not certain about exact logic or expected result, though there are issue with selecting appropriate element and syntax errors 尽管选择适当的元素和语法错误存在问题,但不确定确切的逻辑或预期结果

for (let i = 0; i < numbers.length; i++) {
  numbers[i].addEventListener("click", function(event) {
      // select the `<input>` child element of `entry` here, not `entry[0]`
      // and use `.value` property
      let inputValue = entry.querySelector("input").value;
      // you want `.textContent` here, not `.innerHTML`
      let buttonValue = this.textContent;
      if (buttonValue === "C") {
        entry.innerHTML = "";
      } else {
        entry.innerHTML += buttonValue;
      }   
  }) // include closing `)` at `.addEventListener()` call
}

I just implement Press and Clear function. 我只是实现了按一下和清除功能。

Learn and do it! 学习做吧!

1.Add id for inputfield 1.为输入字段添加ID

<div class="number" id="entry"><input id="entryText" type="number"></div>

2.Do it! 2.做吧!

let numbers = document.getElementsByClassName("number");
let entryText = document.getElementById("entryText");

for (let i=0; i<numbers.length; i++) {
    numbers[i].addEventListener("click", function(event){
    let buttonValue = event.toElement.innerText;
        if (buttonValue === "C") {
            entryText.value = "";
        } else {
            entryText.value += buttonValue;
        }
     });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM