这是字符串:
var numbers = "1,2,3,4,5,6,7,8,9,10";
我希望将此字符串分开并插入到html中。
每次刷新页面时,数字应逐个迭代。
编辑:抱歉,忽略上面这一行。如果我点击了一个按钮,它应该遍历字符串并逐个显示。
任何人都可以帮我这么做吗?
答案 0 :(得分:2)
参考这个小提琴:
单击按钮:
<button onclick='clicked()'>ClickMe</button>
function clicked(){
var numbers = "1,2,3,4,5,6,7,8,9,10";
var c= numbers.split(','); //Split a string into an array of strings
for(var i=0;i<c.length;i++)
alert(c[i]);
}
答案 1 :(得分:2)
试试这个,
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n=numbers.split(','),
i=0;
$('#button').on('click', function(){
$('#show').text(n[i++]);
if(i==n.length) i=0;
});
<强> HTML 强>
<div id="show"></div>
<button id="button">Increment me</button>
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n = numbers.split(','),
i = 0;
$('#button').on('click', function() {
$('#show').text(n[i++]);
if(i==n.length) i=0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<button id="button">Increment me</button>
如果你想要它在画布上,那就试试吧,
<强> Jquery的强>
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n=numbers.split(','),
i=0;
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.font="18px Arial";
$('#button').on('click', function(){
ctx.clearRect(0,0,300,300);
ctx.fillText(n[i++],20,20);
});
<强> HTML 强>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<button id="button">Increment me</button>
希望,这有帮助,
var indexLetter=0;
function paintletter(retryletter) {
var chars = charscontainer.innerHTML.split('');
// comment the blow code
/*letter = retryletter ||
chars[parseInt(Math.random() * chars.length,10)]; */
// add the below code
letter = retryletter ||
chars[indexLetter++];
if(indexLetter==chars.length) indexLetter=0;
c.width = container.offsetWidth;
......
答案 2 :(得分:1)
HTML:
<div id="x"></div>
<button id="y">---</button>
JS:
var numbers = "1,2,3,4,5,6,7,8,9,10";
$('#y').click(function () {
numbers.split(",").forEach(function(n, i) {
console.log(n + ' ' + i);
setTimeout(function() {
$('<p>').text(n).appendTo('#x');
}, i * 200);
});
});
答案 3 :(得分:1)
您可以使用默认功能
p,
var array = numbers.split(",");
数组将是一个普通的javascript数组
答案 4 :(得分:1)
var numbers = "1,2,3,4,5,6,7,8,9,10";
$(numbers.split(',')).each(function(){
$('#main').append('<div>' + this + '</div><br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main"></div>
答案 5 :(得分:0)
使用.split(',')这将返回按,
var numbers =&#34; 1,2,3,4,5,6,7,8,9,10&#34 ;;
$("button").on('click', function () {
var spltValue = String(numbers).split(",");
for (var i = 0; i < spltValue.length; i++) {
var aData = spltValue[i];
console.log(aData);
}
});
<强> JsFiddle 强>
答案 6 :(得分:0)
var numbers = "1,2,3,4,5,6,7,8,9,10";
var dataArray = numbers.split(",");
推送到数组并相应地处理它。