什么是jQuery相当于这个sf悬停suckerfish代码?

时间:2010-05-04 03:16:18

标签: javascript jquery

这个sf hover suckerfish代码的jQuery相当于什么?

<script>
sfHover = function() {
   var sfEls = document.getElementById("navbar").getElementsByTagName("li");
   for (var i=0; i<sfEls.length; i++) {
      sfEls[i].onmouseover=function() {
         this.className+=" hover";
      }
      sfEls[i].onmouseout=function() {
         this.className=this.className.replace(new RegExp(" hover\\b"), "");
      }
   }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
</script>

2 个答案:

答案 0 :(得分:4)

$(function(){         // equivalent to [.ready()][1] syntax (i.e. fire on load)
  $('#navbar li').hover(  // attach hover event to any li descendant of element with id=navbar
    function(){$(this).addClass('hover')},    // $(this) signifies the li element that was hovered over, so we add the 'hover' class to it
    function(){$(this).removeClass('hover')}  // then remove it onmouseout
  );
});

没有冲突版本:

$.noConflict();
jQuery(document).ready(function($) {
  $('#navbar li').hover(
      function(){$(this).addClass('hover')},
      function(){$(this).removeClass('hover')}
    );
});
// Code that uses other library's $ can follow here.

答案 1 :(得分:1)

除了@john Rashh的回答,您还可以单独处理鼠标悬停和鼠标输出功能......

$(document).ready(function() {

   $("#navbar li").mouseover(function() {
      $(this).addClass("hover");
   });

   $("#navbar li").mouseout(function() {
      $(this).removeClass("hover");
   });

});