我有这样的代码:
<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>但它不起作用
发布于 2011-11-01 01:29:06
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.id替换了$(this).attr('id')。
发布于 2011-11-01 01:29:38
你的服务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';发布于 2011-11-01 01:32:10
在这里有效:http://jsfiddle.net/Skooljester/T887t/变量名中没有-,并且在将-的id添加到变量时忘记添加a。
https://stackoverflow.com/questions/7957276
复制相似问题