I would really appreciate if somebody could help me. I am trying to dynamically build a collapsible block with jQuery mobile 1.2 Beta (using jQuery 1.7.1).
Now I have the problem that I want to have an button inside a collapsible header and all works fine but when I click on the button the click event I set on it is not fired but instead the block gets uncollapsed or collapsed.
$('#main').append('<div data-role="collapsible" data-theme="c" data-content-theme="c" id="pflicht_'
+ identifier + '" pflichtID="' + val.guid + '">' +
'<h3 style="white-space: normal;" id="inner_header_' + identifier + '">'
+ header + ': ' + val.pflichtBezeichnung + ' (' + val.Intervall + ' - ' + val.IntModus + ') '
+ val.pflichtNummer + '.' + val.pflichtZusatz +
'<button type="button" data-inline="true" id="ok" pflichtID="'
+ val.guid + '" identifier="' + identifier + '" >Ok</button></h3>' +
'</div>'
$("#ok").live('click', function () {
alert("ok");
});
What do I have to do to get the click event of the button?
Thanks for your help!
First off you should realize that
.livehas been deprecated in favor of on.That said to understand what’s going on here you need to understand how event delegation works in general and
livein particular, when you use event delegation you bind your event to a higher level in the DOM (some parent element) and then because events bubble up you check the originating event to see if it matches the specified selector.The
.livemethod works by binding the event to thedocument(so it is always bound to a parent element) and then when an event bubbles up to thedocumentit checks to see if it matches the selector specified. The issue in your case is that something (probably the collapisple header) is swallowing up theclickevent so that it never reaches the document.The solution is pretty simple, either bind directly to the button, or delegate to a lower level in the DOM, somewhere where your event will reach.
For example
If you don’t want the header to expand and collapse when you click the button, just stop the event from bubbling up further, which you can do using the stopPropagation() method
For example