Jquery:变量ID选择器不起作用

时间:2011-04-26 08:26:12

标签: jquery jquery-selectors global-variables

好的,这是我的代码:

$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不喜欢这个选择器:

$('#' + $tabularID)

虽然我将其更改为:

$('#27')

它警告我的变量$ tabularID就好了,所以我知道它不是错误的变量($ tabularID的输出是27)。我需要一个变量,因为父ID会根据鼠标悬停而改变。

任何人都可以看到我不能做到的事情?可能很明显。

3 个答案:

答案 0 :(得分:7)

您的身份证号码必须以字母a-z或A-Z开头。

此代码$('#'+ $ tabularID)仅在您第一次运行时受到影响。这意味着你的$ tabularID = 0。

当鼠标悬停在它上面时,只更新$ tabularID值,但它不会更新绑定到此对象的事件$('#'+ $ tabularID)

我认为您可以像这样更改代码:

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

            });

    });

答案 1 :(得分:2)

我经常在选择器中使用变量。所有这些对我来说都很好。只是避免使用像'123'这样的ID。 ID命名规则:

  • 必须以字母A-Z或a-z
  • 开头
  • 可以跟着:字母(A-Za-z),数字(0-9),连字符(“ - ”),下划线(“_”),冒号(“:”)和句点(“。 “)
  • 值区分大小写

答案 2 :(得分:0)

我也遇到过jQuery的这个问题,但发现常规JavaScript DOM可以处理以数字开头的ID,如果这是问题的话。在这种情况下,这可能会有所帮助,但是如果更改那段代码而不是更改ID的设置方式,则可能值得一看。

document.getElementById(tabularID)

请注意,您最初不需要“#”。

More info on document.getElementById

相关问题