0

I have searched and searched on google and stackoverflow and please redirect me if I'm wrong but nothing has directly addressed what I am looking for.

I made a list of three items and for each one I would like to create an action listener (onclick) that calls a function to window.open(myURL, '_blank') and go to that URL.

    function goToURL (at) {
        window.open(myURL[at], '_blank');
    };
    for (var i = 0; i < document.getElementsByTagName("li").length; i++) {

        document.getElementsByTagName("li")[i].onclick = goToURL(i);
    }

Now not only does it ignore the onclick, but it opens up all the URL's at once. I checked the documentation and it calls for just the function name no (). But even when there is no parameter it doesn't work. So if I can't pass a param, there is no way for me to assign different URL's. I understand there might be another method for me to do this, but something just as simple as passing a parameter I should be able to figure it out.

http://jsfiddle.net/gymbry/7MG7P/

Thanks in advance!

gymbry
  • 25
  • 4

1 Answers1

1

You have to assign a function to onclick. You are calling the function immediately and assign the return value to it. If you didn't have to pass an argument to the function, you could just do:

document.getElementsByTagName("li")[i].onclick = goToURL;

Note that there are no () after the function name. We are not calling the function, we are only referring to the function itself.

If you want to pass an argument that depends on the loop variables, you have to be aware of the "closure in a loop" problem.

Eventually you can do something like this:

document.getElementsByTagName("li")[i].onclick = (function(i) {
    return function() {
        goToURL(i);
    };
}(i));

Since you tagged the question with jQuery, you could simplify this to:

$('li').each(function(i) {
    $(this).data('url', myURL[i]);
}).click(function() {
    window.open($(this).data('url'), '_blank');
});
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143