overriding JQuery .click() function
i'm having a bit of a prblem with the jquery click function, belo开发者_高级运维w is part of the layout of my code:
<td id="01" class="day-main-diary">
<div title="sdfsdf" class="diary-event ui-corner-all">
<span id="delete"></span>
<div class="diary-event-title ui-corner-all">
sdfsdf
</div>
<div class="diary-event-body ui-corner-all">
<p class="hyphenate">sdfsdf</p>
</div>
</div>
</td>
The title, text in diary-event-title and text in diary-event-body are all dynamically generated and the class 'day-main-diary' has a click function bound to it (the actual code in the js file is:
$('.day-main-diary').click(function(){
// Code is here
}
i am looking for a way for a click event to be recognised on the span with the id of 'delete', amongst other things i have tried
$('.day-main-diary #delete').click(function(){
and
$('#delete').click(function(){
however, each time it completely ignores this event and always calls the day-main diary click event.
can anyone help me? i will be eternally greatfull -Matt
First, remember that there can only be one #delete
ID on the page. If there's more than one, you'll have issues, and should make it a class .delete
.
If the #delete
element isn't present when the page loads (dynamic) you can use .live()
, which will take care of handling the event for you, no matter when you add the element.
$('#delete').live('click', function(){
...
});
But note that this will still fire the event on the .day-main-diary
as well.
One other option would be to call .delegate()
on the .day-main-diary
(as long as it is there when the page loads). This is similar to .live()
but is more localized.
$('.day-main-diary').delegate('#delete', 'click', function() {
...
});
This also will fire the click
on the .day-main-diary
. Not sure what the expected behavior is.
- http://api.jquery.com/live/
- http://api.jquery.com/delegate/
Yet another option would be to test the e.target
of the click in the .day-main-diary
click handler. If it is the #delete
do one thing, if not, do another.
$('.day-main-diary').click(function( e ) {
if(e.target.id === 'delete') {
// run code for the delete button
} else {
// do something else
}
});
Otherwise, still assuming that the #delete
is dynamic, you can bind the .click()
when you create it.
$('<span id="delete">delete</span>').click(function( e ) {
// your code
// uncomment the line below if you don't want the
// click event to fire on .day-main-diary as well
// e.stopPropagation()
})
.appendTo('day-main-diary');
精彩评论