Search code examples
jqueryjquery-selectorsglobal-variables

Jquery: variable as ID selector not working


Ok here is my code:

$tabularID = 0;
$('a.swfselector').live('mouseover', function(event) {
            $tabularID= $(this).parent().attr('id');
            $(this).parent().children().not(this).find('.tab').each(function() {
                      $(this).fadeTo(100, 0.4)
            })
            $(this).find('.tab').each(function() {
                      $(this).fadeTo(100,1)
            })

    });
$('#' + $tabularID).live('mouseleave', function(event) {
            alert($tabularID);
            $(this).children().find('.tab').each(function() {
                      $(this).fadeTo(100,1)
            })

    });

Jquery doesn't like this selector:

$('#' + $tabularID)

Although if I change it to:

$('#27')

It alerts my variable $tabularID just fine, so I know it isn't the variable that is wrong (Output of $tabularID is 27). I need a variable here because the parent ID changes depending on which they mouseover.

Anyone can see what I can't? probably really obvious.


Solution

  • Your ID must begin with a letter a-z or A-Z.

    This code $('#' + $tabularID) is only affected at the first time you run it. It means your $tabularID = 0.

    When you mouse over it only update the $tabularID value, but it will not update the binding to event of this object $('#' + $tabularID)

    I think you can change your code like this:

    $tabularID = 0;
    $('a.swfselector').live('mouseover', function(event) {
                $tabularID= $(this).parent().attr('id');
                $(this).parent().children().not(this).find('.tab').each(function() {
                          $(this).fadeTo(100, 0.4)
                })
                $(this).find('.tab').each(function() {
                          $(this).fadeTo(100,1)
                })
    
                $('#' + $tabularID).live('mouseleave', function(event) {
                    alert($tabularID);
                    $(this).children().find('.tab').each(function() {
                          $(this).fadeTo(100,1)
                    })
    
                });
    
        });