$(document).on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
// code...
});
.live()
is just binding document as listener.
My two cents are that you can almost always find a better listener than document
. At bare minimum, almost all pages use a main content wrapper. This eliminates nodes in the header, footer, and sometimes sidebars as listeners.
The best way to use .on
as a delegating function is to identify the nearest common ancestor that is expected to never be destroyed or otherwise have events unbound. For example, if you have a form that gets updated and changed by ajax requests, the listener could be the form node itself (if only the contents of the form are updated) or a container element (generally a div) that surrounds the form. If such a div isn't there, you could always add it in, or you could just go up the tree to the next ancestor.
[edited to add:]
In the particular sample code provided, it's hard to say if there's a better listener that would contain both #header
and also #sb-sec
. But imagining that these things share an ancestor with the id "mainContainer", your more efficient code simply swaps out the listener:
$('#mainContainer').on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
// code...
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…