2

I have dynamically created <li> links through javascript, but while creating onclick event I am not able to pass argument to a function. Please find the script below which is working without argument.

function printa() { $('#output').html(yDev[0]); }

for(var n=0;n<sns.length;n++) {
$("#ulDev").append('<li><a href="#" id=btnDev'+n+'>'+sns[n]+'</a></li>');
document.getElementById('btnDev'+n).onclick=printa
}

I need to use something like the below with arguments in function

function printa(m) { $('#output').html(yDev[m]); }

for(var n=0;n<sns.length;n++) {
$("#ulDev").append('<li><a href="#" id=btnDev'+n+'>'+sns[n]+'</a></li>');
document.getElementById('btnDev'+n).onclick=printa(n)
}

I have tried the following options but no luck.
1. onclick in <a> tags
2. $('#btnDev'+n).addEventListener('click', printa(n))
3. $("#btnDev"+n).on("click", function(evt){ evt.preventDefault(); printa(n); })

Kindly advice on how to proceed or any alternate method.

Suresh Raju
  • 76
  • 10

2 Answers2

2

Firstly, don't use incremental id attributes. It's a pain to maintain. Instead, attach information thats unique to each element using data attributes. The common classname will also then allow you to use a single delegated event handler. Try this:

for (var n = 0; n < sns.length; n++) {
    $("#ulDev").append('<li><a href="#" data-sns="' + n +'">' + sns[n] + '</a></li>');
}

$('#ulDev').on('click', 'a', function(e) {
    e.preventDefault();
    var sns = $(this).data('sns');
    $('#output').html(yDev[sns])
});

var sns = [ 'foo', 'bar' ];
var yDev = {
  0: 'foooooooo',
  1: 'baaaaaaar'
}

for (var n = 0; n < sns.length; n++) {
    $("#ulDev").append('<li><a href="#" data-sns="' + n +'">' + sns[n] + '</a></li>');
}

$('#ulDev').on('click', 'a', function(e) {
    e.preventDefault();
    var sns = $(this).data('sns');
    $('#output').html(yDev[sns])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulDev"></ul>

<div id="output"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Instead of using plaintext appended to your parent element, you need to create the element with jquery so jquery knows it exists.

See this answer here for how to do that

Community
  • 1
  • 1
PBLC
  • 259
  • 2
  • 12
  • This is not the case. You can insert the element however you like in to the DOM. jQuery will have no knowledge if it either way in this case as it was appended after the DOM was loaded. – Rory McCrossan Jul 07 '15 at 15:03