简体   繁体   English

如何在 JavaScript 中的一个函数中显示每个按钮

[英]How to display each buttons in one function in JavaScript

So, I'm trying to build a calculator and the first thing I want to do is to display all the buttons in my output.所以,我正在尝试构建一个计算器,我想做的第一件事就是在我的输出中显示所有按钮。 I have created a function called displayButtons and inside, I got the first 2 buttons by id however, when I try to display them, only the number 2 displays.我创建了一个名为 displayButtons 的函数,在里面,我通过 id 获得了前 2 个按钮,但是,当我尝试显示它们时,只显示数字 2。 One way to fix this is to create a function for each numbers and then it'll work but that's not what I want.解决此问题的一种方法是为每个数字创建一个函数,然后它会起作用,但这不是我想要的。 I've also tried nesting the functions for each number within a function, but I wasn't able to call it properly onclick.我也尝试过将每个数字的函数嵌套在一个函数中,但我无法在点击时正确调用它。 Any ideas?有任何想法吗? Thanks in advance!提前致谢!

HTML code: HTML 代码:

<div id="output"></div>
        <div class="numbers">
            <button value="1" id="one" onclick="displayButtons()">1</button>
            <button value="2" id="two" onclick="displayButtons()">2</button>

JS code: JS代码:

function displayButtons() {

    var one = document.getElementById("one").value;
    document.getElementById("output").innerHTML = one;


    var two = document.getElementById("two").value;
    document.getElementById("output").innerHTML = two

}

Have you tried a for loop?你试过for循环吗? you'd be able to add a click functionality with a closure or 'let' keyword or a separate function.. run the following in codepen, see how it works and if this is something that can be useful.您可以使用闭包或“let”关键字或单独的函数添加单击功能。在 codepen 中运行以下命令,看看它是如何工作的,以及这是否有用。


    function createButtons() {
       //let is block scoped, not function scoped
        for (let i = 1; i <= 5; i++) {
          var body = document.getElementsByTagName("BODY")[0];
          var button = document.createElement("BUTTON");
          button.innerHTML = 'Button ' + i;
          button.onclick = function() {
               alert('This is button ' + i);
          }
          body.appendChild(button);
        }
     }
      
     createButtons();

There is multiple solutions for this, but here a simple one: you can use the event data to get the info of the button clicked, then you can do what you want with these values.有多种解决方案,但这里有一个简单的解决方案:您可以使用事件数据来获取单击按钮的信息,然后您可以使用这些值做您想做的事情。

HTML HTML

<div id="output"></div>
<div class="numbers">
  <button value="1" id="one">1</button>
  <button value="2" id="two">2</button>
</div>

JS JS

document.querySelectorAll('.numbers button').forEach(button => { 
  button.addEventListener('click', (e) => {
    console.log(e.target.id, e.target.value)
  })
})

To display the output on clicking of numbers, you can pass in a this object inside the function like this要在单击数字时显示输出,您可以像这样在函数内传入this对象

<button value="1" id="one" onclick="displayButtons(this)">1</button>

and when you click on it, you'll receive the button node inside the function full code would be当您单击它时,您将收到函数内的按钮节点完整代码将是

   <div class="numbers">
        <button value="1" id="one" onclick="displayButtons(this)">1</button>
        <button value="2" id="two" onclick="displayButtons(this)">2</button>
    </div>


    <script>
        function displayButtons(button) {
            document.getElementById("output").innerHTML += button.value
        }
    </script>

You keep overwriting the innerHTML , to that's why you only see the 2.您不断覆盖innerHTML ,这就是为什么您只看到 2.

I recommend that you change your approach.我建议你改变你的方法。 All of your buttons are in div.numbers .您所有的按钮都在div.numbers中。 Add a single click event listener to the numbers div.将单击事件侦听器添加到数字 div。 This event listener will fire if any of the buttons are pressed, because the click event bubbles.如果按下任何按钮,此事件侦听器将触发,因为单击事件会冒泡。 This is called event delegation .这称为事件委托

In the click event handler, you can see which button has been clicked and add the value of the clicked button to div#output .在 click 事件处理程序中,您可以查看单击了哪个按钮并将单击按钮的value添加到div#output

 const output = document.querySelector('#output'); const numbers = document.querySelector('.numbers'); numbers.addEventListener('click', ({ target }) => { if (!target.hasAttribute('value')) { return; } output.textContent += target.value; });
 <div id="output"></div> <div class="numbers"> <button value="1">1</button> <button value="2">2</button> <button value="3">3</button> <button value="4">4</button> <button value="5">5</button> </div>

Each time you press a button, you're overwriting the entire innerHTML, so you're replacing the whole content by the new one.每次按下按钮时,您都会覆盖整个 innerHTML,因此您将用新内容替换整个内容。

You should append the value instead, using += operator您应该使用 += 运算符附加值

Furthermore you may consider to use innerText instead of innerHTML, and use addEventListener instead of onclick=此外,您可以考虑使用 innerText 代替 innerHTML,并使用 addEventListener 代替 onclick=

<div id="output"></div>
<div class="numbers">
    <button value="1" id="one">1</button>
    <button value="2" id="two">2</button>
</div>

... and after ... ... 之后 ...

<script>
document.querySelector(".numbers").addEventListener('click', e => {
    if( e.target.nodeName === "BUTTON" )
        document.getElementById("output").innerText += e.target.value;
});
</script>

You have to get the id of every button in onclick parameter like: onclick= displayButtons(id) it will create different click event for every buttton then您必须在 onclick 参数中获取每个按钮的 id,例如: onclick= displayButtons(id) 它会为每个按钮创建不同的点击事件然后

function displayButton(id){
let oldValue = document.getElementById("output").innerHtml
document.getElementById("output").innerHTML = oldValue + id;}

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

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