本文翻译自:How can I process each letter of text using Javascript?
I would like to alert each individual letter of a string, but I am unsure how to do this. 我想提醒一个字符串的每个字母,但是我不确定该怎么做。
So, if I have: 所以,如果我有:
var str = 'This is my string';
I would like to be able to separately alert T, h, i, s, etc. This is just the beginning of an idea that I am working on, but I need to know how to process each letter separately. 我希望能够分别警告T,h,i,s等。这仅仅是我正在研究的一个想法的开始,但是我需要知道如何分别处理每个字母。
I want to use jQuery and was thinking I might need to use the split function after testing what the length of the string is. 我想使用jQuery,并考虑在测试字符串的长度后可能需要使用split函数。
Ideas? 有想法吗?
参考:https://stackoom.com/question/8fzm/如何使用Javascript处理每个字母
If you want to animate each character you might need to wrap it in span element; 如果要为每个角色设置动画,则可能需要将其包装在span元素中;
var $demoText = $("#demo-text");
$demoText.html( $demoText.html().replace(/./g, "$&").replace(/\s/g, " "));
I think this is the best way to do it, then process the spans. 我认为这是最好的方法,然后处理跨度。 ( for example with TweenMax) (例如,使用TweenMax)
TweenMax.staggerFromTo( $demoText.find("span"), 0.2, {autoAlpha:0}, {autoAlpha:1}, 0.1 ); TweenMax.staggerFromTo($ demoText.find(“ span”),0.2,{autoAlpha:0},{autoAlpha:1},0.1);
One possible solution in pure javascript: 纯JavaScript的一种可能的解决方案:
for (var x = 0; x < str.length; x++)
{
var c = str.charAt(x);
alert(c);
}
You can access single characters with str.charAt(index)
or str[index]
. 您可以使用 str.charAt(index)
或str[index]
访问单个字符 。 But the latter way is not part of ECMAScript so you better go with the former one. 但是后一种方法不是ECMAScript的一部分,因此您最好选择前一种。
You can try this 你可以试试这个
var arrValues = 'This is my string'.split('');
// Loop over each value in the array.
$.each(arrValues, function (intIndex, objValue) {
alert(objValue);
})
You can get an array of the individual characters like so 您可以像这样获得单个字符的数组
var test = "test string",
characters = test.split('');
and then loop using regular Javascript, or else you can iterate over the string's characters using jQuery by 然后使用常规Javascript循环,否则您可以使用jQuery通过以下方式迭代字符串的字符:
var test = "test string";
$(test.split('')).each(function (index,character) {
alert(character);
});