[英]How to add digits to different spans with JavaScript?
I have a variable which counts an amount of elements: 我有一个计算元素数量的变量:
var n = 0;
Now, if I make 现在,如果我做
n++;
i want to apply this number to different digits: 我想将此数字应用于不同的数字:
<span class="n">-</span>
<span class="n">-</span>
<span class="n">-</span>
<span class="n">-</span>
If i have the number 10, I want: 如果我的数字是10,我想:
<span class="n">-</span>
<span class="n">-</span>
<span class="n">1</span>
<span class="n">0</span>
How can i do this? 我怎样才能做到这一点?
I want to build my own counter. 我想建立自己的柜台。 I can use jQuery / JavaScript or whatever the Web has to offer. 我可以使用jQuery / JavaScript或任何网络必须提供的东西。
You want to split the digits into an array and assign accordingly: 您想将数字分割成一个数组并进行相应分配:
var n = 101;
n++;
var digits = (""+n).split("");
Now you have an array digits
that you can assign out: 现在,您可以分配一个数组digits
:
digits[0] = 1
digits[1] = 0
digits[2] = 2
Update Just an idea, instead of creating the SPAN's ahead of time, you could use a container and create them dynamically: 更新只是一个想法,您可以使用容器并动态创建它们,而不必提前创建SPAN:
<div id="counter"></div>
function setCounter(n) {
digits = (""+n).split("");
digits.forEach(function(index){
$("#counter").append("<span class='digit'>"+index+"</span>");
});
}
Here is a working JSFiddle using the code above. 这是使用上面的代码的有效JSFiddle 。
Try this code: 试试这个代码:
var n = 0,
placeholders = document.getElementsByClassName('n');
function updateView(number) {
('' + number).split('').reverse().forEach(function(el, i) {
placeholders[placeholders.length - i - 1].innerHTML = el;
});
}
Pass any number in this function and its digits will be placed in proper positions. 在此函数中传递任何数字,其数字将放置在适当的位置。 Eg: 例如:
updateView(85); // => --85
(sorry, I don't know how to name this function better) (对不起,我不知道如何更好地命名此函数)
I am assuming from your example that your counter never goes above four digits. 我从您的例子中假设您的计数器永远不会超过四位数。 So we can convert the number to a string and build markup by iterating over its characters. 因此,我们可以将数字转换为字符串,并通过迭代其字符来构建标记。
I made a jsfiddle to demonstrate http://jsfiddle.net/H4wQ8/ 我做了一个jsfiddle来演示http://jsfiddle.net/H4wQ8/
But the core of it is this javascript: 但是它的核心是这个javascript:
var n = 0;
function buildCounter(number)
{
var markup = '';
var numberString = String(number);
for (var i = 0; i < 4 - numberString.length; i++)
{
markup += '<span class="n">-</span>';
}
for (var i = 0; i < numberString.length; i++)
{
markup += '<span class="n">' + numberString[i] + '</span>';
}
$('#counter').html(markup);
}
$(function ()
{
$('#incrementButton').on('click', function ()
{
n++;
buildCounter(n);
});
buildCounter(n);
});
We use a helper function to build the markup, and jquery to place it in the appropriate container. 我们使用一个辅助函数来构建标记,并使用jquery将其放置在适当的容器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.