[英]How can I wrap each character from a text node in a <li>?
I want to split a string value in a single digits and wrap()
it in <li></li>
. 我想将一个字符串值拆分为一个数字并将其wrap()
在<li></li>
。 I am trying to achieve this goal but fail to do this following is my code: 我正在尝试实现此目标,但以下是我的代码无法做到这一点:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(e) { var str = $('#number').html(); var spl = str.split(''); var len = spl.length; var i = 0; setInterval(function() { if (i <= len) { $('#number').wrap('<li>' + spl[0] + '</li>') } i++; }, 200) }) </script> <div id="number">123456 as</div>
here spl[0]
this always selects the first index of array (split)... use spl[i]
在这里, spl[0]
总是选择数组的第一个索引(分割)...使用spl[i]
try this 尝试这个
var str = $('#number').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function () {
if (i < len) {
if (spl[i] != " ") { //checking for the space here
$('#number').append('<li>' + spl[i] + '</li>')
//-^^^^^^----------^^^^^^-----here
}
}
i++;
}, 200)
If you're trying to move each character from the text into a <li>
, then here's an alternative solution that splits the text nodes in place and wraps them: 如果您尝试将每个字符从文本移到<li>
,那么这里是一个替代解决方案,该方法将文本节点拆分就位并包装它们:
//- Get a reference to the raw text node
var txt = $('#number').contents()[0];
setTimeout(function repeat(){
if (txt.nodeValue.length) {
//- Split the text node after the first character
txt = txt.splitText(1);
//- txt is now the latter text node, so wrap the former with a <li>
$(txt.previousSibling).wrap('<li>');
//- Rinse and repeat
setTimeout(repeat, 200)
}
},200);
Also, I swapped your setInterval
for a setTimeout
because your timer would have run indefinitely, whereas this stops when the sequence is complete. 另外,我将setInterval
替换为setTimeout
因为您的计时器将无限期地运行,而当序列完成时,它将停止。
Here's one splitting backwards for fun: 这是一个向后拆分的乐趣:
var txt = $('#number').contents()[0];
setTimeout(function (){
if (txt.nodeValue.length) {
$(txt.splitText(txt.nodeValue.length - 1)).wrap('<li>');
setTimeout(arguments.callee, 200)
}
},200);
See also: 也可以看看:
try this: 尝试这个:
var str = $('#number').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function(){
if(i <= len )
{
if(spl[i] !== undefined && spl[i] !== " "){
$('#number').wrap('<li>'+spl[i]+'</li>')
}
}
i++;
},200);
working fiddle here: http://jsfiddle.net/n5Brh/1/ 在这里工作的小提琴: http : //jsfiddle.net/n5Brh/1/
DO NOT wrap with html content only html tag is allowed in wrap() 不要用html内容换行wrap()中只允许html标签
here is your ans jsfiddle 这是你的ans jsfiddle
$(document).ready(function(e) {
var str = $('#number').html();
var spl = str.split(' ');
var len = spl.length;
var i = 0;
if(i <= len )
{
$('#number').wrap('<li id="dd"> </li>')
}
i++;
$('#number').text(spl[0]);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.