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.

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.