Web10--jQuery进阶
在这个问题中,我们需要使用jQuery来创建一个简单的图片库。这个图片库应该能够在点击下一张或上一张按钮时更换显示的图片。
解决方案1:
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$(".next").click(function(){
var imgSrc = $("#imageGallery img").attr("src");
var lastDigit = parseInt(imgSrc.substr(imgSrc.length - 1));
var nextDigit = (lastDigit + 1) % 3;
var newSrc = "image" + nextDigit + ".jpg";
$("#imageGallery img").attr("src", newSrc);
});
$(".previous").click(function(){
var imgSrc = $("#imageGallery img").attr("src");
var lastDigit = parseInt(imgSrc.substr(imgSrc.length - 1));
var nextDigit = (lastDigit - 1 + 3) % 3;
var newSrc = "image" + nextDigit + ".jpg";
$("#imageGallery img").attr("src", newSrc);
});
});
</script>
</head>
<body>
<p>Click the buttons to change the image in the gallery.</p>
<button class="previous">Previous</button>
<div id="imageGallery">
<img src="image1.jpg" />
</div>
<button class="next">Next</button>
</body>
</html>
在这个解决方案中,我们使用jQuery的.attr()方法来改变图片的src属性,从而更换显示的图片。
解决方案2:
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var currentIndex = 0;
$(".next").click(function(){
currentIndex = (currentIndex + 1) % images.length;
$("#imageGallery img").attr("src", images[currentIndex]);
});
$(".previous").click(function(){
currentIndex = (currentIndex - 1 + images.length) % images.length;
$("#imageGallery img").attr("src", images[currentIndex]);
});
});
</script>
</head>
<body>
<p>Click the buttons to change the image in the gallery.</p>
<button class="previous">Previous</button>
<div id="imageGallery">
评论已关闭