0

I'm creating anchor tags dynamically and I want them to call a function that has a set parameter for each one.

Example:

<div class="AnchorHolder">
   <a onclick="someFunction(1)">someText</a>
   <a onclick="someFunction(2)">someText</a>
   <a onclick="someFunction(3)">someText</a>
</div>

I've tried

$("#AnchorHolder").append("<a>" + someText + "</a>").click(function (e) {
    someFunction(someIntVariable);
});

but instead connects all of the anchors to the IntVariables current value, whereas I wanted the previous ones.

How can I accomplish this?

0

3 Answers 3

1

Well, I would suggest you to try data attributes. As far I know they are made for that porpuse. See:

$("#AnchorHolder").append("<a href='#' data-myvar='" + someIntVariable + "'>" + someText + "</a>");

// Keep the event binding out of any loop, considering the code above will be called more than once...
$("#AnchorHolder").on('click', 'a', function (e) {
    alert($(this).data("myvar"));
});

Fiddle

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

Comments

1

If you just want the click on the new element, tack it onto that element, and not on the #AnchorHolder element:

var newAnchor = $("<a>" + someText + "</a>").click(function (e) {
  someFunction(someIntVariable);
});
$("#AnchorHolder").append(newAnchor);

Or, alternatively to get each <a> to call the someFunction with their postion-inside-the-div:

$("#AnchorHolder a").each(function(idx) {
  var a = $(this);
  a.click(function() { someFunction(idx); });
});

1 Comment

Well I tried it now and the older anchors are not able to call the function, just the latest one. Any idea why?
1

You can always create a html element as following

   $('<a>').attr("onclick","fun('hi')").html('Some text').appendTo("#AnchorHolder");

Hope this helps

1 Comment

@Kelsey Abreu : did this help you?

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.