0

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);
8
  • Have you never heard of a.onclick = ...? Or better still a.addEventListener(...);? Remember to lock the scope of k though, otherwise it won't work as you expect. Commented Jan 14, 2016 at 13:02
  • @nietthedarkabsol but the OP is creating a string and setting it as the onclick string attribute, k is creating different strings each iteration of the loop. Commented Jan 14, 2016 at 13:07
  • @JuanMendes Yes, hence the need to scope k appropriately. Commented Jan 14, 2016 at 13:07
  • @farhawa to should post an example that runs, right now it looks like it should work, even though you should not be setting handlers through attributes Commented Jan 14, 2016 at 13:08
  • You could just set a data-* attribute to your k value and then in your myFunction access it to get your value, instead of trying to create multiple onclick values Commented Jan 14, 2016 at 13:15

4 Answers 4

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

What you are saying is true but it's only a problem if you set the onclick to a function that shares a closure. The OP did was not making use of closures in their handlers, their handler is a string that gets evaled by the browser
0
<script>
  function myFunction(value) {
    alert(value);
  }
</script>

<ul id="my-list"></ul>

<script>
  var args = {
    a: 1,
    b: 2,
    c: 3
  };

  for (var arg in args) {
    var li = document.createElement('li');
    var a = document.createElement('a');
    a.setAttribute('href', '#');
    a.setAttribute('onclick', 'myFunction(' + args[arg] + ')');
    a.appendChild(document.createTextNode(arg));
    li.appendChild(a);
    document.getElementById('my-list').appendChild(li);
  }
</script>

Comments

0

You can use the event delegation to simplify event handling.

ul.onclick = function(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;
    // check here if it's your link 
    console.log(target.htef);
};

So your full code could be somthing like:

var args = [1,2,3,4,5,6,7,8],
    ul = document.querySelector(".list");

for (var k in args) {
    var li = document.createElement("li");
    var a = document.createElement("a");

    a.setAttribute("href", "#" + k);
    a.appendChild(document.createTextNode(k))
    li.appendChild(a);

    ul.appendChild(li);
}

ul.onclick = function(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;

    console.log(target.htef);
};

JSFiddle

Comments

0

Your code works fine, you just weren't appending your nodes to the document.

window.myFunction = function(val) {
  console.log('Clicked ' + val);
}
var LIST_OF_ARGUMENTS =  ['a','b', 'c', 'd'];
var ul = document.querySelector('ul');
// Shouldn't use `for in` with arrays, this is just 
for (var k=0; k < LIST_OF_ARGUMENTS.length; k++) {
  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(LIST_OF_ARGUMENTS[k]))
  li.appendChild(a);
  ul.appendChild(li)
}
<ul></ul>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.