用于多次单击的jquery快捷方式
jquery shortcut for multiple clicks
我对js/编程还是个新手。无论如何,可以指导我如何优化我的代码吗?我确信有多种方法可以编写一个小而快速的代码来做同样的事情。
$('.ourservices-content .left ul li:nth-child(1)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '0px'
},800)
})
$('.ourservices-content .left ul li:nth-child(2)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-600px'
},800)
})
$('.ourservices-content .left ul li:nth-child(3)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-1200px'
},800)
})
$('.ourservices-content .left ul li:nth-child(4)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-1800px'
},800)
})
$('.ourservices-content .left ul li:nth-child(5)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-2400px'
},800)
})
$('.ourservices-content .left ul li:nth-child(6)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-3000px'
},800)
})
$('.ourservices-content .left ul li:nth-child(7)').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-3600px'
},800)
})
这应该做到:
$('.ourservices-content .left ul li').each(function (index) {
$(this).click(function () {
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: '-' + (600 * index) + 'px';
}, 800);
});
});
我们正在做的是循环遍历原始$()
调用中选择器匹配的每个元素。然后,对于每个匹配的元素,我们从第零个元素开始调整动画参数marginLeft,即我们所处的元素索引。
我能想到几种方法,但最简单的方法是将其封装在function
中,将数据排列在array
中,然后在for
循环中调用function
:
function animate_box(count,margin) {
$('.ourservices-content .left ul li:nth-child('+count+')').click(function(){
$('.our-services-content-box > ul.box').stop().animate({
marginLeft: margin+'px'
},800)
})
}
var left_margin=0;
var indexes=[1,2,3,4,2,2];
for(var i=0;i<indexes.length;i++) {
animate_box(indexes[i],left_margin);
left_margin-=600;
}
我没有办法尝试,但这样的想法。。。
var $items = $('.ourservices-content .left li');
for (var i = 0, len = $items.length; i < len; i++) {
$items.eq(i).click(function () {
$('.box').stop().animate({
marginLeft : '-=600';
}, 800)
})
}
相关文章:
- javascript中的快捷方式融合优化
- 用于导出导入的快捷方式
- 如何制作链接到网页特定元素的桌面快捷方式
- 如何启用Emmet'的选项卡键处理程序(HTML快捷方式)
- 使用全局快捷方式(如 Spotlight/Launchy)将电子应用程序带到前台
- 有没有一种快捷方式可以让我用javascript或jQuery设置对象的字段
- 用我自己的自定义快捷方式覆盖浏览器快捷方式
- 创建一个键盘快捷方式来启动Google Chrome扩展
- Chrome扩展和Chome浏览器中的Jquery工作方式不同
- 触发器快捷方式”;STRG+Plus按钮”;使用Javascript
- Jquery/javascript方式发送50个表单,就像发送1个表单一样
- 动态网页的快捷方式
- 下划线/洛达什号中的快捷方式,用于(递归)设置对象的所有属性
- 用于发送 ajax/JSON 请求的 JQuery 快捷方式
- jQuery:使用 var 快捷方式分配数据以及如何链接功能以在加载和单击时运行
- 是否有一个jQuery函数来“快捷方式”if/else开关
- JQuery 焦点,无需输入关键事件快捷方式
- 用于多次单击的jquery快捷方式
- 谁能解释一下现成的jQuery快捷方式的源代码
- 类的类似jquery的编程快捷方式