简体   繁体   English

JavaScript:For-Loop无法正常工作

[英]JavaScript: For-Loop not working properly

I got the following code (I got it from here ): 我得到了以下代码(我从这里得到了它):

$( "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>" ));
     }
   }
});

It's part of a function that is working fine. 它是功能正常的一部分。 Only when I add that for-Loop it fails. 只有当我添加for-Loop时它才会失败。

The Problem: When I console.log(i) it increments as expected. 问题:当我在console.log(i)它按预期递增。 When I alert(i) , it alerts 0-4 for six times. 当我发出alert(i) ,它会警告0-4六次。 Also, i isn't added to the numberX class. 此外, i没有添加到numberX类。 Looking at the DOM, i is always zero. 看看DOM, i总是零。 What's wrong with the loop? 循环有什么问题?

In your for loop when i==0 , this in the DOM has been replaced by your new <span> element, but in JavaScript context, this still refers to your original element. 在你for循环,当i==0this在DOM已被新的所取代<span>元素,但是在JavaScript方面, this仍然是指你的原始元素。 That's why further replacement won't work and the class is stuck at 0 . 这就是为什么进一步替换不起作用并且课程停留在0

Let's say for example your original element is a <div> : 比方说,例如你的原始元素是<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)

Because after i==0 , this is already off the DOM. 因为在i==0 ,这已经脱离了DOM。 So further replacement don't work. 所以进一步替换不起作用。

A way to correct your code will be: 更正代码的方法是:

$("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/ http://jsfiddle.net/KVm9C/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM