0

I am dynamically generating a series of onclick events where an alert() is associated with loop number of the pretended content. My problem is that currently the alerts outputs the 'i' value of the last loop rather than the i'th loop associated with the pretended content. Any thoughts?

JavaScript:

for (i = 1; i < 4; i++) {

    prepend_content = '<a href="#" id="img1_link_' + i + '" onclick="alert(i);">foo</a>';
    $('#dynamic_div').prepend(prepend_content);

}

Many thanks.

2 Answers 2

2

Try concatenating it like you do before:

for (i = 1; i < 4; i++) {
    prepend_content = '<a href="#" id="img1_link_' + i + '" onclick="alert(' + i + ');">foo</a>';
    $('#dynamic_div').prepend(prepend_content);
}

You might want to declare i and prepend_content (with var) in case you already haven't, to make sure they don't leak into the global scope.

At the same time, I wouldn't suggest using or adding HTML with inline event handlers. Try creating the element like this:

prepend_content = $("<a>").attr({
    href: "#",
    id: "img1_link_" + i
}).text("foo").on("click", (function (i) {
    return function () {
        alert(i);
    };
})(i));

DEMO: http://jsfiddle.net/ujv4y/

The extra use of the immediately invoked function for the click handler is to make a closure that captures the value of i in the loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Concatanate is exactly what I needed. Thanks! : )
@user1497338 No problem, glad it helped! Let me know if you need more help with this :)
0

You can create a function using currying for the alert (for more complex stuff):

function(i) {
return function(){alert(i);}
}

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.