I’m trying to use JQuery’s on() function to attach an event to a button and any button that will be dynamically created and injected later on. However, when I run the test website, it calls alertMe() without clicking the button. alertMe is in a .js file and of course, I have the JQuery file. This is about as simple an example as I can create – am I missing something here with attaching this event with JQuery?
<body>
<script src="Scripts/JScript.js" type="text/javascript"></script>
<script src="Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').on("click", alertMe());
});
</script>
<form id="form1" runat="server">
<div id="1">
<button data-attr="1">
Say Sumfin'</button>
</div>
</form>
</body>
data-attr is just a custom attribute that I’ll use to identify the buttons I’ll be attaching this too.
EDIT
So the reason the question was asked will remain evident, I’ve left it as-is. But this is what I used to actually have the event properly attach to dynamically added elements.
$(document).on('click', '[data-attr]', alertMe);
This:
The
.on()method expects a function reference as its second argument. Notice the difference: