简体   繁体   中英

jQuery + ASP.NET: jQuery click event doesn't fire

I'm having an issue using JQuery within an ASP.NET website. I want to bind a common click handler to multiple similar elements (generated through a ListView for those familiar with ASP.NET). My assumption was to use a class selector as follows (as an example):

$('.standard-group').click(function () {
    alert($(this).attr("id"));
});

This relates back to a series of divs having this class:

<div class="standard-group">
    some content
</div>

<div class="standard-group">
    some other content
</div>

Furthermore, the content is generated inside a ContentPlaceholder and merged into a master page (2 nested master pages actually). I've tried putting the click handler between <script></script> tags inside a second ContentPlaceholder that injects it's content into the <head> section of the page, tried putting it with the content in the main ContentPlaceholder all to no avail. What ends up happening is that the generated page loads correctly and I can inspect the source and see the function there, but no event is raised. I suspect it's something to do with the master page/server processing scenario, but can't pinpoint it.

Any help out there?

delegate the click event to document with on()

 $(document).on('click','.standard-group',function () {
    alert($(this).attr("id"));
});

link to read more about on()

Your script for adding event could be executing before the element being created, you can use on() to delegate event to document.

$(document).on('click', '.standard-group', function () {
    alert($(this).attr("id"));
});

delegated events

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next. Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM