0

I have this part of code:

for (i = 0; i <= texte.split(';')[1].split(',').length - 1; i++) {
        cell = document.createElement("td");
        cell.setAttribute("width", "10%");
        cell.setAttribute("align", "center");
        if (texte.split(';')[1].split(",")[i] != "")
            cell.onclick = function () { chgnom('1',"'" + texte.split(';')[1].split(",")[i] + "'",''); };
        textnode = document.createElement("span");
        textnode.innerHTML = texte.split(';')[1].split(",")[i];
        cell.appendChild(textnode);
        row.appendChild(cell);
    }

The call to texte.split(';')[1].split(",")[i] in innerHTML returns 'HELLO', but the one in function return 'undefined'. Could someone help me with this?

Thank you

3
  • 2
    Could you show us a demo on JSFiddle.net? Commented Jul 17, 2012 at 12:45
  • your example needs to have more information in it. IF it is underfined, you might be splitting on something which doesnt exist for example. Commented Jul 17, 2012 at 12:47
  • whats the value of texte ? and where is row variable decalred ? Commented Jul 17, 2012 at 12:48

2 Answers 2

4

Lets assume arr=texte.split(';')[1].split(','). When your click will be executed, i will be already equal to arr.length.arr[arr.length] is undefined,and that was what you got. Workaround could be something like a:

if (texte.split(';')[1].split(",")[i] != ""){
    cell.onclick = (function(inner_i){
        return function () { 
            chgnom('1',"'" + texte.split(';')[1].split(",")[inner_i] + "'",''); 
        };
    })(i);
}
Sign up to request clarification or add additional context in comments.

1 Comment

He was already using a closure, what you have posted is a closure that returns a closure. Use the terms properly, because a closure is not a function that returns a function, but a dynamically assigned function which may or may not be returned inside another function, and which in turn may or may not be a closure.
0

Have you test your texte.split(';')[1].split(",")[i] for each loop ? Try to put that in variable before.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.