0

I'm trying to create an unordered list menu but can't get the onclick to call the proper function. How do I pass the object's keys through the onclick function?

function ulMenu(menuList) {

    for (var keys in menuList) {
        var li = document.createElement("li");

        var textNode = document.createTextNode(keys);
        li.appendChild(textNode);

        li.onclick = function() { ?keys? };

        ul.appendChild(li);
    }

    var element = document.getElementsByTagName("body")[0];
    element.appendChild(ul);
}

window.onload = function() {
    ulMenu({Register: Register,"Sign In": Login});
    }

function Login() {
    alert("Login Function");
}

function Register() {
    alert("Register Function");
}
Robert Peek
  • 201
  • 1
  • 2
  • 4

1 Answers1

0

You will need to read about how closures works in JavaScript, but here's the answer:

li.onclick = (function (keys) {
    return function () {
        //handler code
        console.log(keys);
    };
})(keys);

Something more efficient would be to create a function outside of the loop that will be responsible for generating your handler.

function createClickHandler(keys) {
    return function () {
        //use keys
    };
}

Then in the loop:

li.onclick = createClickHandler(keys);
Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90