我的 switch 语句有问题。我在这里简化了一点,但我的项目是一个图片库,当您单击一张图片时,该图片就会加载。基本 html 很简单:
html:
<section id="content">
<div id="container">
<img src="Images/Image1.jpg" id="#image" class="bigImage" />
<div id="info">Title1</div>
</div> <!-- end of container -->
</section> <!-- end of content -->
画廊的 html:
<section id="content">
<div id="container">
<div id="gallery" class="sections">
<img src="Images/Image1.jpg" class="thumbnails">
<img src="Images/Image2.jpg" class="thumbnails">
<img src="Images/Image3.jpg" class="thumbnails">
etc...
</div>
</div> <!-- end of content -->
</section> <!-- end of container -->
执行此操作的函数:
$( document ).on('click', '.thumnails', function(e){
var imageSource = $(this).attr('src');
$( '#container' ).remove();
$( '#content').load('index.html' + ' #content', function(){
$( '#image' ).attr('src', imageSource);
}).hide().fadeIn('slow');
});
这一切都运行良好。现在我想更新包含每张图片标题的#info div 的内容。为此,我创建了一个包含 switch 语句的简单函数:
function updateInfo(number){
switch(number) {
case 1:
$( '#info').text('Title1');
break;
case 2:
$( '#info').text('Title2');
break;
case 3:
$( '#info').text('Title3');
break;
etc...
}
}
然后,我通过添加对该函数的调用来更新原始事件监听器,如下所示:
$( document ).on('click', '.thumbnails', function(e){
var imageSource = $(this).attr('src');
$( '#container' ).remove();
$( '#content').load('index.html' + ' #content', function(){
$( '#image' ).attr('src', imageSource);
counter = imageSource.match(/\d+/g);
updateInfo(counter);
}).hide().fadeIn('slow');
});
这不起作用。图像已更新,但标题未更新,并且始终显示:Title1。
我做了一些测试来了解原因。我在 updateInfo 函数中添加了一条alert()语句,如下所示:
function updateInfo(number){
alert(number);
switch(number) {
case 1:
$( '#info').text('Title1');
break;
case 2:
$( '#info').text('Title2');
break;
case 3:
$( '#info').text('Title3');
break;
etc...
}
}
这是有效的,这意味着当我单击图片时,在显示该图片之前,我会收到一个警告框,其中包含我单击的图片的编号,因此我知道该函数正在被调用并且参数正在被传递。但是当我移动警报(数字)时; case 子句之一内的语句,如下所示:
function updateInfo(number){
switch(number) {
case 1:
$( '#info').text('Title1');
break;
case 2:
alert(number);
break;
case 3:
$( '#info').text('Title3');
break;
etc...
}
}
我没有收到警报框。我对编程还很陌生,所以这可能是一个基本错误。感谢您抽出时间。
最佳答案
为了避免冲突,因为变量号将是一个字符串。通过将大小写值包含在引号内来更改代码,如下所示。
function updateInfo(number){
switch(number) {
case '1':
$( '#info').text('Title1');
break;
case '2':
$( '#info').text('Title2');
break;
case '3':
$( '#info').text('Title3');
break;
etc...
}
}
关于javascript - switch语句不接收参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654156/