Jquery:启用/禁用功能? (绑定/取消绑定?)最好的方法是什么?
我有一个函数 Stickyhead() ,它基本上将 h2 固定在页面顶部,当您向下滚动页面时,当您到达新的 h2 时,h2 中的文本会发生变化,所以它就像 iphone 的电话簿/联系人或安卓手机。当您滚动浏览名称以 A 开头的联系人时,带有字母 A 的标题将固定在顶部,然后当您到达 B 名称时,会将页面顶部标题中的文本更改为 B。我想在 .switch
标签选择了类时启用/禁用此功能。下面的代码工作得很好,但我想知道这是否是一个不好的方法?我是否多次重新加载我的函数?有更好的方法吗?
$('.switch').click(function() {
if ($('.switch label').hasClass('selected')) {
stickyhead();
} else {
$(window).unbind('scroll');
}
});
I have a function stickyhead() that basically keeps an h2 fixed at the top of the page, as you scroll down the page the text in the h2 changes as you reach a new h2, so it's like the phonebook/contacts of an iphone or android phone. A header with the letter A will stick to the top as you scroll through your contacts that have names starting with A, then it changes the text in the header at the top of the page to B when you reach the B names. I want to enable/disable this when .switch
label has class selected. The code below work just fine, but I'm wondering if this is a bad way to do it? Am I reloading my function multiple times? Is there a better way to do it?
$('.switch').click(function() {
if ($('.switch label').hasClass('selected')) {
stickyhead();
} else {
$(window).unbind('scroll');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
但请记住,在不需要时不解除绑定处理程序会浪费内存。
绑定/解除绑定虽然丑陋,但在资源稀缺时是合理的。
另外,当元素被删除并且处理程序保持绑定状态时...... Viola!内存泄漏的完美案例。可能看起来无关紧要,但我觉得我应该提到这一点,以防万一您正在为移动平台编写此内容。
But do keep in mind, not unbinding handlers when predictably not required is a waste of memory.
Binding/Unbinding are ugly but justifiable when resources are scarce.
Also, when elements are removed and handlers remain binded... Viola! Perfect case for memory leaks. Might seem irrelevant, but just felt I should mention this, just in case you're writing this for mobile platforms.
我在可视化您的代码方面略有困难,但您不太可能需要不断地绑定和解除绑定。您的滚动处理程序中应该有一个布尔值,它有条件地运行处理程序中的代码:
I'm struggling slightly to visualise your code, but it's unlikely that you need to be constantly binding and unbinding. You should have a boolean in your scroll handler that conditionally runs the code in the handler:
保持函数绑定但使用状态变量来确定 Stickyhead() 是否实际执行任何操作可能更有效。
例如
,然后不要取消绑定函数,只需使用
stickyheadActive=false;
It may be more efficient to keep the function binded but to use a status variable to determine whether
stickyhead()
actually does anything or not.eg
Then rather than unbinding the function just use
stickyheadActive=false;