JavaScript:For循环无法正常工作

JavaScript: For-Loop not working properly

本文关键字:常工作 工作 For 循环 JavaScript      更新时间:2023-09-26

我得到了以下代码(我从这里得到的):

$( "p" ).children().andSelf().contents().each( function () {
  if ( this.nodeType == 3 ) {
    var $this = $( this );
    var regEx = /('w)/g;
    for(i = 0; i < 5; i++){
      $this.replaceWith( $this.text().replace( regEx, "<span class='numbers"+ i +"'>$&</span>" ));
     }
   }
});

这是一个运行良好的函数的一部分。只有当我为Loop添加时,它才会失败。

问题:当我console.log(i)时,它按预期递增。当我alert(i)时,它会提醒0-4六次。此外,i没有添加到numberX类中。查看DOM,i始终为零。循环出了什么问题?

for循环中,当i==0时,DOM中的this已被新的<span>元素替换,但在JavaScript上下文中,this仍然引用原始元素。这就是为什么进一步的替换不起作用,并且类被困在0

例如,假设您的原始元素是<div>:

i     | this  | The same place in DOM
======|=======|======================================
-     | <div> | <div>
0     | <div> | replaced by <span class="number0">
1...5 | <div> | <span class="number0"> (not affected)

因为在i==0之后,这已经脱离了DOM。因此,进一步的更换不起作用。

纠正代码的方法是:

$("div").children().andSelf().contents().each(function(index,item){
    if (this.nodeType == 3) {
        var $this = $(item);
        var arr=$this.text().match(/('w)/g);
        arr.forEach(function(item,i,a){a[i]=item.replace(/(.*)/, "<span class='number"+i+"'>$&</span>");});
        $this.replaceWith(arr.join(""));
    }
});

http://jsfiddle.net/KVm9C/