2011-10-31 77 views
4

显示DIV我有这样的代码:jQuery的:通过动态ID

<ul> 
    <li><a href="#" class="service-chooser" id="ubuntu-one">Ubuntu One</a></li> 
    <li><a href="#" class="service-chooser" id="ftp">FTP account</a></li> 
</ul> 

<!-- these div are hidden --> 
<div id="ubuntu-one-form" class="hide"> 
    Ubuntu One credential 
</div> 
<div id="ftp-form" class="hide"> 
    Ftp Crediental 
</div> 

当我点击一个链接,我想基于链路的ID展示一个div:

<script type="text/javascript"> 
$(document).ready(function() { 

$(".service-chooser").click(function() { 
    var service = $(this).attr('id'); 
    var service-id = '#' + service + 'form'; 

     $(service-id).show('slow', function() { 
      // Animation complete. 
     }); 

    }); 

}); 

</script> 

但它没有在JavaScript中工作

回答

9

变量名称不能含有-。当您打开控制台时,您应该收到错误,类似于missing ; before statement

一个变量名的有效字符是字母数字字符,下划线和美元符号。

您可以通过一个_更换-解决您的代码:

$(".service-chooser").click(function() { 
    var service = this.id   ;   // Example ubuntu-one 
    var service_id = '#' + service + '-form'; // Example #ubuntu-one-form 

     $(service_id).show('slow', function() { 
      // Animation complete. 
     }); 
    }); 
}); 

我也通过this.id取代$(this).attr('id')
参见:When to use Vanilla JavaScript vs. jQuery?

0

服务ID也需要Concat的一个 ' - ' 按你的HTML(<div id="ubuntu-one-form" class="hide">),还为您服务-ID应该SERVICE_ID:这里

$(".service-chooser").click(function() { 
    var service = $(this).attr('id'); 
    var service_id = '#' + service + '-form';