jQuery:通过动态id显示div

时间:2011-10-31 17:27:29

标签: jquery

我有这段代码:

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

但它不起作用

3 个答案:

答案 0 :(得分:9)

JavaScript中的变量名称不能包含-。当您打开控制台时,您应该收到错误,类似于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).attr('id')替换为this.id
另请参阅:When to use Vanilla JavaScript vs. jQuery?

答案 1 :(得分:0)

您的服务ID还需要根据您的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';

答案 2 :(得分:0)

在此处工作:http://jsfiddle.net/Skooljester/T887t/您的变量名称中没有-,并且在将-的ID添加到a时忘记添加{{1}}变量