Javascript / HTML:如何实现在点击时添加点击计数器的按钮?

时间:2018-01-15 18:03:32

标签: javascript html button

我了解如何实施单击计数器。但是,我正在努力弄清楚如何实现一个复制点击计数器的按钮,同时还允许我使用相同的JavaScript代码。

单击计数器的当前布局有一个div用于计数器,然后是一个用于递增的按钮,另一个用于递减。对于按钮,我为每个按钮使用单独的事件监听器。

<div id="counter">0</div>
<button id="increment">+1</button>
<button id="decrement">-1</button>

Javascript:

var incr = document.getElementById('increment');
var decr = document.getElementById('decrement');
incr.addEventListener('click', ...);
decr.addEventListener('click', ...);

我如何实现另一个复制计数器的按钮?另外,我如何处理JavaScript方面?我目前的做法似乎并不适用于多个计数器。

1 个答案:

答案 0 :(得分:0)

To generate a new div you will need to create it and append it to the DOM. Something like:

const myDiv = document.createElement('div');
myDiv.id = 'id-blabla';
document.body.appendChild(div);

You can wrap that in the click handler.

Now, if you want to update several counters at the same time on a single button click, you will need to use another selector, instead of the id. Use a class or similar, like: <div class="counter"></div>, and then in the click handler get all those elements and iterate over them updating the counter value. Does that make sense to you?

(Also, this link I think it will be very helpful for you, in terms of iterating over DOM elements and other concepts).

EDIT: This other answer on DOM manipulation is going to be very useful too!


EDIT2: I understand now that what you want is to be able to generate counters (with the div and the buttons), that will have their click handlers and everything set it up correctly. You can use different approaches here, but the main purpose is to not repeat yourself:

  • You need your buttons to be able to identify the counter div target. You can achieve this using a custom data attribute in your buttons, like: <button class="increase" data-counterId="counter1"></button>. This way you would only need to write the click handler once (on all elements with "increase" or "decrease" class, and in the code extract the counterId data attribute so you would be able to edit the correct div counter.
  • You can achieve the same having some sort of common part in the id's of each block of HTML elements, like counter-1, increase-1 and decrease-1. Then each button would know which index it has, and which index the counter target should have.
  • This definitely looks like a component you could wrap in a Counter class. I don't know how familiar you are with JS UI frameworks, but depending on how complex your system is, you might want to think about using one. I recommend you to take a look to this link that explains React Components. Maybe it is out of scope of what you need, but I think it is worth to mention it.

I think with this information you have a good starting point to decide how you want to implement it, based on the size and complexity of what you want to build. I hope it helps!