苦苦挣扎精简javascript

时间:2015-09-16 05:10:09

标签: javascript jquery

我总是发现自己一遍又一遍地复制和粘贴相同的功能。我很难理解如何编写更灵活的代码。

$(document).on('mouseenter mouseleave','#claps10',function () {
    "use strict";
    if ($(window).width() > 800) {
        $('.inco10').stop().animate({width: 'toggle', height: '125px'});
    }
});

$(document).on('mouseenter mouseleave','#claps11',function () {
    "use strict";
    if ($(window).width() > 800) {
        $('.inco11').stop().animate({width: 'toggle', height: '125px'});
    }
});

当我知道有一个更好的方法只有一个时,我有11个。我只是不够熟练。你怎么称呼它,你能告诉我一个如何做到这一点的样本吗?

2 个答案:

答案 0 :(得分:2)

使用claps选择器获取ID为[id^=claps]的所有元素,然后使用$(this)获取目标元素的ID(例如claps11)remove {{1使用claps从id获取数字(11)然后将其与类连接。

$(this).attr("id").replace("claps", "")

答案 1 :(得分:2)

另一种实现这一目标的方法:

使用mouseenter和mouseleave的类名

$(document).on('mouseenter mouseleave','.claps',function () {
"use strict";
   logicFunction(this.id.replace("claps", "inco");
});
function logicFunction(className)
{

   if ($(window).width() > 800) {
       $('.'+className).stop().animate({width: 'toggle', height: '125px'});
   }
} 
相关问题