首页 文章

选择器元素类更改后重新初始化jQuery函数?

提问于
浏览
0

我有两个jQuery函数,它们为相同的元素提供不同的功能 .

这是我的基本HTML标记:

<ul>
  <li class="active">
    <a href="#head1" data-toggle="tab" class="fade">
      <img src="head1_down.jpg" />
    </a>
  </li>
  <li>
    <a href="#head2" data-toggle="tab" class="fade">
      <img src="head2_down.jpg" />
    </a>
  </li>
  <li>
    <a href="#head3" data-toggle="tab">
      <img src="head2_down.jpg" />
      <!-- Does not fade! No .fade class on link tag. -->
    </a>
  </li>
</ul>

第一个函数 lookFade() 添加了一个淡入淡出效果,可以在鼠标悬停时更改图像的来源:

// Helper functions
$.fn.lookUp = function() {
  $(this).attr('src', function(i,val) { return val.replace('down.jpg', 'up.jpg') });
  return $(this);
}

$.fn.lookDown = function() {
  $(this).attr('src', function(i,val) { return val.replace('up.jpg', 'down.jpg') });
  return $(this);
}

$.fn.lookFade = function() {
  $(this).hover(
    function() {
      $(this).fadeOut(function() {
        $(this).lookUp().fadeIn();
      })
    },
    function() {
      $(this).fadeOut(function() {
        $(this).lookDown().fadeIn();
      })
    }
  );
  return $(this);
}

// Change .active image on pageload
$('li.active > a.fade > img').lookUp();

// Fade effect on hover
$('li:not(.active) > a.fade > img').lookFade();

第二个函数在单击链接项时切换内容窗格(标记中未显示,这有效!) . 它还会更改链接标记内的图像,并将.active类从当前li元素更改为单击的li元素 .

// Toggle tabs and change .active
$('a[data-toggle="tab"]').click(function() {
  var head = $(this).attr('href');
  var active = "#" + $('.pane.active').attr('id');
  if (head != active) {
    $(active).removeClass('active');
    $(head).addClass('active');
    $(this).children('img').lookUp();
    $(this).parent().parent().children('li.active').removeClass('active');
    $(this).parent().addClass('active');
  }
});

Problem: 单击链接时,内容窗格会发生变化,甚至可以正确调整类 . 但 lookFade() 函数对于那些通过点击失去这个课程的人来说并不是很好 .

谢谢阅读 . 我期待着你的帮助:)

1 回答

  • 1

    更改元素的类不会更改绑定到它的事件 . 事件绑定到元素,而不是类 . 如果您想要这种类型的功能,请使用.on().delegate()的事件委派

    由于您使用插件来执行这些操作,因此使其工作并不容易 . 我会抛弃 lookFade 方法并使用事件委托绑定 lookFade 事件( mouseentermouseleave ) .

    快速举例:

    $('ul').delegate('li:not(.active) > a.fade > img','mouseenter',function(){
        $(this).fadeOut(function() {
            $(this).lookUp().fadeIn();
        });
    });
    

相关问题