我有这个代码:
<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>
Run Code Online (Sandbox Code Playgroud)
当我点击链接时,我想根据链接的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>
Run Code Online (Sandbox Code Playgroud)
但它不起作用
JavaScript中的变量名称不能包含-.当您打开控制台时,您应该收到错误,类似于missing ; before statement.
变量名称的有效字符是字母数字字符,下划线和美元符号.
您可以通过替换-a 来修复代码_:
$(".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.
});
});
});
Run Code Online (Sandbox Code Playgroud)
我也换成$(this).attr('id')了this.id.
另请参阅:何时使用Vanilla JavaScript与jQuery?
| 归档时间: |
|
| 查看次数: |
8924 次 |
| 最近记录: |