如何在jquery中编写onclick =“slide(-1)”?

时间:2017-02-22 08:28:00

标签: jquery

我在jquery中制作了一个图像滑块。我第一次用javascript完成,现在我想转换jquery中的代码。

问题是如何在jquery中编写onclick="slide(-1)"

HTML:

<div id="container">
    <img id="img" src="img/img1.jpg">
    <div id="left-holder"><img class="left" src="img/arrow-left.png"></div>
    <div id="right-holder"><img class="right" src="img/arrow-right.png"></div>
</div>

CSS:

#container {
width: 1024px;
height: 768px;
margin: 20px auto;
position: relative;
}

#img {
width: 1024px;
height: 768px;
position: absolute;
}

#left-holder {
height: 768px;
width: 100px;
position: absolute;
left: 0px;
top: 0px;
}

#right-holder {
height: 768px;
width: 100px;
position: absolute;
right: 0px;
top: 0px;
}

.left {
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 0px;
cursor: pointer;
}

.right {
width: 50px;
height: 50px;
position: absolute;
top: 50%;
right: 0px;
cursor: pointer;
}

Jquery:

var imagecount = 1;
var total = 8;
function slide(x){
   var image = $("#img");
   imagecount = imagecount + x;
   if(imagecount > total) { imagecount = 1;}
   if(imagecount < 1) { imagecount = total;}
   image.attr("src", "img/img"+ imagecount + ".jpg");
}
  

图像被称为:img1.jpg,img2.jpg,..

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试更新脚本,如:

var imagecount = 1;
var total = 8;
function slide(x){
   var image = $("#img");
   imagecount = imagecount + x;
   if(imagecount > total) { imagecount = 1;}
   if(imagecount < 1) { imagecount = total;}
   image.attr("src", "img/img"+ imagecount + ".jpg");
}
$(document).ready(function(){
    $("#left-holder").click(function(){
        slide(-1);
    });
    $("#right-holder").click(function(){
        slide(1);
    });
});

有关绑定点击的详细信息,您可以查看此链接JQuery Click API