I am attempting to attach an event handler to a dynamically created DOM element in the following way:
var createdElement = $('<a>', {
click: function (data) {
alert("click");
}
});
This works as expected, but now I want to pass a variable to the click function. Can anyone suggests how to do this.
Thecodeparadox’s answer works in the general case, but always passes the same value to the
clickhandler, regardless of the<a>element on which it was triggered.If you want the value to depend on the clicked element, you can call on() on the element itself:
However, the code above uses a different syntax than the one in your question. If you want to keep defining the
clickhandler in a property/event map, you can use data() to associate a value with the element once and for all:(Note that I added calls to
appendTo("body")so the new element becomes part of the DOM and theclickevent gets a chance to be triggered. Feel free to ignore this if you’re adding the element to the DOM later in your code.)