开发者

jQuery class selector oddness

I'm using jQuery to change the background image of a button depending on the class associated with it on hover. It only works if I put the hover statements in separate functions, however. Why is this?

Here's the NON working code, always evaluates to the .submit hover statement, even when that class is removed via the keyup event.

    $(function() {
    {

$('.submit-getinfo').hover(function ()
{
    $(this).css( {backgroundPosition: "right bottom"} );
}, function() {
    $(this).css( {backgroundPosition: "right top"} );
    //$(this).removeClass('submithover');

});

$('.submit').hover(function ()
{
    $(this).css( {backgroundPosition: "left bottom"} );
}, function() {
    $(this).css( {backgroundPosition: "left top"} );
    //$(this).removeClass('submithover');

});

    }});

Working code:

    $(function() {
    {


$('.submit').hover(function ()
{
    $(this).css( {backgroundPosition: "left bottom"} );
}, function() {
    $(this).css( {backgroundPosition: "left top"} );
    //$(this).removeClass('submithover');

});
    }});

    $('#test').bind('keyup', function() { 

    if (url == 'devel') {
    $("#submit").addClass("submit-getinfo").removeClass("submit");

$('.submit-getinfo').hover(function ()
{
    $(this).css( {backgroundPosition: "right bottom"} );
}, function() {
    $(this).css( {backgroundPosition: "right top"} );
//$(this).removeClass('submithov开发者_高级运维er');

});
    } } );

I just fail to see why I have to put the hover statements in separate functions, instead of sticking both in the main DOM.


You need to re-arrange your code a bit using .live(), like this:

$(function() {
  $('.submit-getinfo').live('mouseenter', function () {
      $(this).css( {backgroundPosition: "right bottom"} );
  }).live('mouseleave' function() {
      $(this).css( {backgroundPosition: "right top"} );
  });

  $('.submit').live('mouseenter', function () {
      $(this).css( {backgroundPosition: "left bottom"} );
  }).live('mouseleave', function() {
      $(this).css( {backgroundPosition: "left top"} );
  });
});

Currently it's saying "find elements with that class, bind this hover function to those", now it doesn't matter that you're changing the class, because the function's already bound to that element's mouseenter and mouseleave jQuery events...even if it's class changes, which is unrelated.

With .live() however, the event handler isn't bound to the element itself, it's bound to the document, waiting for the mouseenter and mouseleave events to bubble up, it evaluates if the element causing the events matches the selector right now, and executes if that's the case...so if you change the class it will matter, make sense?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜