在JavaScript中运行循环的麻烦

I have created a function for splitting values and run in a for loop but the for loop terminates after a single loop.

If I have an array with 4 items then it runs only one time:

function color_change() {
    //alert(document.getElementById("dom-target"));
    var div_fgh = document.getElementById("dom-target");
    var myData = div_fgh.textContent;
    //alert(myData);
    alert(myData);
    var stall_wished= myData;
    var array_WW= stall_wished.split(",");
    alert(array_WW.length);
    for (j=0;j<array_WW.length;j++){
        var wished_stalls = array_WW[j];
        alert(wished_stalls);
        document.getElementById(wished_stalls).style.background="#F90";
    }

}

  1. http://jsfiddle.net/40y8a3p3/

see the console you get an error in it.

Uncaught TypeError: Cannot read property 'style' of null

this is because there is no element defined with ids 1 , 2 , 3 , 4 , 5

so for the first time it gets into loop gives you an alert then there is error and it breaks.

define all the ids, and it will work

here it is :http://jsfiddle.net/40y8a3p3/1/

  1. And according to what dsfq pointed out in another answer, I have another option of solving it, if there is a space( characters which results into array of string that don't exactly match elements ids) inside the text you can see this http://jsfiddle.net/40y8a3p3/3/

Edit: According to OP's comment below, I made some changes to the code.. http://jsfiddle.net/vkgg9rg1/10/ I just need to trim the white spaces before finding the element by ID , since it may contain white spaces.

The problem seems to be in untidy result of string split operation. Very likely that there are spaces around , characters which results into array of string that don't exactly match elements ids. So as the result document.getElementById(wished_stalls) returns null and loop fails after the first round.

Use regexp in split method:

var array_WW = stall_wished.split(/\s*,\s*/);

Here is the demo where you can see the difference http://jsfiddle.net/ngy28ky2/

function color_change()
{
//alert(document.getElementById("dom-target"));
var div_fgh = document.getElementById("dom-target");
  var myData = div_fgh.textContent;
   // var myData = div_fgh.value;// use value if is input type.
console.log(myData);

var stall_wished= myData;
    var array_WW= stall_wished.split(",");
for (var j=0;j<array_WW.length;j++){

var wished_stalls = array_WW[j];

document.getElementById(wished_stalls).style.background="#F90";
}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dom-target">1,2,3,4,5</div>
<div id="1" style="width:10px;height:10px;border: 2px solid;"></div>
<div id="2" style="width:10px;height:10px;border: 2px solid;"></div>
<div id="3" style="width:10px;height:10px;border: 2px solid;"></div>
<input type="button" onclick="color_change()" value="Click"/>

see if you are trying something like this:

</div>