I have generated few elements in my page using following method. For example,
$("#button"+caption).click(function(){ var firstDisplay = '<div id="firstDisp'+caption+'"><ul>'; for(var i=0;i<parents.length;i++){ firstDisplay=firstDisplay+'<li class="fClick">'+parents[i]+'</li>'; } firstDisplay=firstDisplay+'</ul></div>'; $(firstDisplay).dialog(); });
and when i create an onclick event for 'fClass' like so :
$(".fClick").click(function(){ alert("hey!"); });
It does not works ! However, if i put the onclick function inside the other function, right after .dialog(), it works ! I have a lot of elements created this way, so I cannot put all onclick events in a single method. Is there any way around this? I am having the same problem with .append method as well.
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.
Change it to .on
or .delegate
based on the version of jQuery you are using..
As of jQuery 1.7+
$(document).on('click', '.fClick', function(){ alert("hey!"); });
For older jQuery versions use delegate
$(document).delegate('.fClick', 'click', function(){ alert("hey!"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With