Save jQuery callback functions in a separate file
Probably I missed something, but lets say I have this:
$('a.delete').click(function(){
resp=window.confirm("Are you sure you wa开发者_开发知识库nt to delete this?");
if(resp)
return true;
else
return false;
}
Now, I want to save that callback function into a separate js file, because I will use it in several pages. My logic told me to do this:
$('a.del').click(delete_element());
Having my js file like this:
function delete_element(){
resp=window.confirm("Are you sure you want to delete this?");
if(resp)
return true;
else
return false;
}
This doesn't work. Everytime my page loads, it displays the confirm window, even if I haven't clicked the link.
It is clear that my logic failed this time. What am I missing?
$('a.del').click(delete_element());
That is calling the function delete_element() and hoping for a function to be returned.
$('a.del').click(delete_element);
That (note the missing ()) will set the click handler to delete_element.
try;
$('a.delete').click(function(){
delete_element()
}
edit
I'd be passing the reference to the element to remove to the delete_element function and removing it from there as the name of the function says delete_element not ask_to_delete_element.
How about
function deleteElement() {
return window.confirm("Are you sure you want to delete this?");
}
$('a.delete').click(deleteElement);
Or if this is standard behavior for your pages:
$('a.delete').live('click', function() {
return window.confirm("Are you sure you want to delete this?");
});
精彩评论