2

我想将字符串值拆分为单个数字,并将wrap()其拆分为<li></li>. 我正在努力实现这一目标,但未能做到以下是我的代码:

<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>

4

5 回答 5

1

在这里,spl[0]这总是选择数组的第一个索引(拆分)...使用spl[i]

尝试这个

 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)

在这里摆弄

于 2013-09-02T10:54:24.017 回答
1
<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').append('<li>'+spl[i]+'</li>')

            }
        i++;

        },200)
})
</script>

参考附加

于 2013-09-02T10:51:46.303 回答
1

如果您试图将文本中的每个字符移动到 a<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);

http://jsfiddle.net/9wRbe/

另外,我把你换成setInterval了 asetTimeout因为你的计时器会无限期地运行,而当序列完成时它会停止。

这是为了好玩而向后拆分的一个:

var txt = $('#number').contents()[0];

setTimeout(function (){
    if (txt.nodeValue.length) {
        $(txt.splitText(txt.nodeValue.length - 1)).wrap('<li>');

        setTimeout(arguments.callee, 200)
    }
},200);

http://jsfiddle.net/9wRbe/1/

也可以看看:

于 2013-09-02T11:08:37.323 回答
0

DO NOT wrap with html content only html tag is allowed in wrap()

here is your 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]);
})
于 2013-09-02T11:16:59.477 回答
0

尝试这个:

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);

在这里工作小提琴:http: //jsfiddle.net/n5Brh/1/

于 2013-09-02T10:54:02.243 回答