Search code examples
javascripthtmlhref

set onclick attribute with dynamic arguments


I want to create dynamic list of hrefs using JavaScript, for that I need the link to execute some function each time the user click on the href BUT with different arguments.

Code: What I tried so far is this!

    for(var k in LIST_OF_ARGUMENTS){
            var li = document.createElement("li");
            var a = document.createElement("a");
            a.setAttribute("href","#");
            // K here is the argument of myFunction 
            a.setAttribute("onclick","myFunction("+k+")")
            a.appendChild(document.createTextNode(k))
            li.appendChild(a);

Solution

  • The below code will work, making k the correct variable for the onclick event.

    If you don't create the onclick handler separately but instead do a.onlick = myFunction(k); inside the for loop, k will be the last value of k in the for loops iteration for each a element (every click event will fire the same function using the same value of k).

    function doClick(a, k) {
       a.onclick = function() {
          myFunction(k);
       }
    };
    for (var k in LIST_OF_ARGUMENTS) {
       var li = document.createElement("li");
       var a = document.createElement("a");
       doClick(a, k);
       a.setAttribute("href", "#");
       // K here is the argument of myFunct
       a.appendChild(document.createTextNode(k))
       li.appendChild(a);
    }