我遇到了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');
});
,这是行不通的。图像得到更新,但标题没有,它总是显示:标题1。
我已经做了一些测试,看看为什么。我已经把警报()语句updateInfo时函数内部,像这样:
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...
}
}
而且这样的作品,这意味着,当我点击一张图片,显示的画面,我得到一个警告框的号码前我点击图片,所以我知道该函数正在调用,参数正在传递。但是当我移动警报(数字)时;声明内的其中一个案例条款,如下所示:
function updateInfo(number){
switch(number) {
case 1:
$('#info').text('Title1');
break;
case 2:
alert(number);
break;
case 3:
$('#info').text('Title3');
break;
etc...
}
}
我没有看到提示框。我对编程还很陌生,所以这可能是一个基本的错误。谢谢你的时间。
嗨。感谢您的回答。我已经尝试了两件事,但他们没有解决问题。我在脚本的另一个地方调用了同样的函数updateInfo(),它在那里工作,但是当我改变它就像你说它既不能在 – Paul
中工作,我已经用代码示例更新了我的答案。我建议在switch语句中添加一个'default'的case,这样你就可以看到你实际得到的是什么'number'。 –