jQuery切换焦点/模糊的兄弟姐妹

所以我现在有这个并且它有效,但是我想知道在编写移动网站时是否有最佳的写作方式,如果有重要的话,还有性能。

想想在元素下滑下(切换)的工具提示,我在页面上也有大约30个工具提示div,因为这将用于多个元素

JS:

$('.mobile-tool-tip').each(function() { $(this).hide(); $(this).prev().focus(function() { $(this).next().slideToggle('fast'); }); $(this).prev().blur(function() { $(this).next().slideToggle('fast'); }); }); 

HTML for mobile-tool-tipfunction

 
Valid format 999-999-9999. Please include the area code.

一直在使用这个(感谢亨特 )切换元素,但不能让它与下一个()工作,我不想用手编写每个工具提示div

 $("[name=field_name]").change(function() { var show = $(this).val(); $("#hidden_div").toggle(show); }); 

一些建议:

  • 使用CSS保存几毫秒隐藏.mobile-tool-tip元素。
  • 将事件附加到父div。 找到父元素比找到兄弟姐妹更快。
  • 当你在寻找nextprev元素时,它是一个特定元素,我总是建议使用`nextAll(“。mobile-tool-tip”)
  • 你花时间寻找$(this).prev() 。 不要两次。 jQuery中的许多函数返回对最后一个查询的引用,这使您可以链接调用(类似$(".anElement").hide().remove() )。 利用它来节省时间。
  • 当您有一个focus动作和其他blur ,使用确定性方法隐藏/显示或启用/禁用元素。 这将确保您不会错过任何活动或特殊场合,并防止任何与之相关的错误。

所以:

 $('.mobile-tool-tip').each(function() { $(this).prev().focus(function() { $(this).nextAll(".mobile-tool-tip").slideDown('fast'); }).blur(function() { $(this).nextAll(".mobile-tool-tip").slideUp('fast'); }); 

});

祝好运!

一些简单的想法。

  1. 您可以缓存选择器并将调用链接在一起,以避免对dom进行任何迭代。
  2. 您还可以在焦点和模糊函数中创建尖端的闭包,这将导致无需额外的dom迭代。

所以你最终会得到这样的东西……

 $('.mobile-tool-tip').each(function() { var $tip = $(this); $tip.hide().prev().focus(function() { $tip.slideToggle('fast'); }).blur(function() { $tip.slideToggle('fast'); }); }); 

jsfiddle在使用闭包触发事件时显示出轻微的性能提升。

您可以尝试通过使用变量来保存$(this).next()元素,从而将一些调用组合到DOM中。 根据文件的大小,这可以减少大量时间,而不必进行两次调用。

 var nextElement = $(this).next(); $(this).prev().blur(function(){ $(nextElement).slideToggle(); }