[英]javascript switch case not working properly?
i have the following code and i am using switch case to switch the src of the pictures with a button.. i don't know why the first case's "alert" is not functoning.. 我有以下代码,并且我使用开关盒来通过按钮切换图片的src。.我不知道为什么第一种情况的“警报”没有起作用。
<div id="main_img">
<center>
<button style="width:100;height:100" onClick="LastPic();"><---</button>
<img id="img" src="13.jpg" height=70% width=70%>
<button style="width:100;height:100" onClick="FirstPic();">---></button>
</div>
<script>
var james = document.getElementById("img").getAttribute('src');
document.write(james);
function FirstPic(){
switch (james){
case "12.jpg":
document.getElementById("img").src = "13.jpg";
break;
case "13.jpg":
document.getElementById("img").src = "14.jpg";
break;
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
}
</script>
Your problem is that the james variable is the same every time you call your function, it needs to be updated. 您的问题是,每次调用函数时james变量都相同,因此需要对其进行更新。
<div id="main_img">
<center>
<button style="width:100;height:100" onclick="LastPic();"><---</button>
<img id="img" src="13.jpg" height=70% width=70%>
<button style="width:100;height:100" onclick="FirstPic();">---></button>
<div id="imagesrc">13.jpg</div>
</div>
<script>
function FirstPic(){
var james = document.getElementById("img").getAttribute('src');
var imagesrc=document.getElementById('imagesrc');
switch (james)
{
case "12.jpg":
james = "13.jpg";
break;
case "13.jpg":
james = "14.jpg";
break;
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
imagesrc.innerHTML=james;
document.getElementById('img').src=james;
}
</script>
add type of button type="button" 添加按钮类型type =“ button”
<button type="button" style="width:100;height:100" onClick="FirstPic();">---></button>
add attribute type="button" in button so page is not postback 在按钮中添加属性type =“ button” ,因此页面不会回发
Try this its working fine. 试试这个工作正常。
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function myFunction()
{
var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);
switch (src)
{
case "12.jpg":
document.getElementById("img").src = "13.jpg";
break;
case "13.jpg":
alert('sa');
document.getElementById("img").src = "14.jpg";
break;
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
}
</script>
<div id="main_img">
<button style="width:100;height:100" onClick="LastPic();"><--- </button>
<img alt="example" id="img" class="imagess" src="13.jpg" height=70% width=70%>
<button style="width:100;height:100" onClick="myFunction();">---></button>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.