开发者

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.


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)
                })

            });

    });


I often use variables in selectors. And all works fine for me this way. Just avoid using IDs like '123'. ID naming rules:

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")
  • Values are case-sensitive


I've also encountered this problem with jQuery. But found out that regular JavaScript DOM can handle ID's that start with numbers, if that's the problem. This might not help in this case, but it might be worth looking at if it is easier to change that piece of code, rather than changing how your ID's are set up.

document.getElementById(tabularID)

Note that you don't need '#' in the beginning.

More info on document.getElementById

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜