javascript - Jquery - 为常见任务编写函数时出现问题

标签 javascript jquery

我有以下菜单系统代码,其中包含每个菜单项中常见的许多部分。

我正在努力将通用代码放入函数中,然后我可以根据需要调用这些函数 - 因此我不需要数百行相同的代码。

有人能帮我指出正确的方向吗?

$("#test1").hover( function() {

    $(this).animate({
        width: "599px",
        left: "0px",
        height: "168px",
        backgroundColor: "#d7df23",
        opacity: 0.95
    }, 100).css({'z-index': "10", 'border-top': 'none'});

// Start of common code     
        $(this).find(".thumb").animate({
            width: "150px",
            height: "150px",
            marginTop: "8px",
            marginRight: "0px",
            marginBottom: "0px",
            marginLeft: "12px"
        }, 100).attr('src','images/home/animatedMenu/1IMG.jpg').css({'border': '1px solid #FFF'});
// End of common code

    $(this).find("h2").animate({
        left: "600px"
    }, 100).hide();

    $(this).find(".moredetail").delay(150).animate({
        left: "0px"
    }, {
        duration: 150,
        easing: 'easeInBounce'
    });

}, function() {

    $(this).clearQueue().animate({
        width: "246px",
        left: "9px",
        height: "83px",
        backgroundColor: "#222",
        opacity: 0.90
    }, 100).css({'z-index': "1", 'border-top': '1px solid #444'});

    // Start of common code
    $(this).find(".thumb").animate({
        width: "68px",
        height: "68px",
        marginTop: "6px",
        marginRight: "0px",
        marginBottom: "0px",
        marginLeft: "13px"
    }, 100).attr('src','images/home/animatedMenu/1IMGup.jpg').css({'border': '1px solid #000'});
// End of common code

    $(this).find("h2").show().animate({
        left: "0px"
    }, {
        duration: 350,
        easing: 'easeOutBounce'
    });

    $(this).find(".moredetail").animate({
        left: "600px"
    }, 100);

}); 

最佳答案

将每个重用的代码片段分解到函数中。您将拥有两个像这样的函数:

function thumbHoverStart(element) {
  $(element).find(".thumb").animate({
        width: "150px",
        height: "150px",
        marginTop: "8px",
        marginRight: "0px",
        marginBottom: "0px",
        marginLeft: "12px"
  }, 100)
  .attr('src','images/home/animatedMenu/1IMG.jpg')
  .css({'border': '1px solid #FFF'});
}

从适当的事件调用每个函数:

// ...
    opacity: 0.95
}, 100).css({'z-index': "10", 'border-top': 'none'});

thumbHoverStart(this);

$(this).find("h2").animate({
    left: "600px"
// ...

关于javascript - Jquery - 为常见任务编写函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940821/

相关文章:

javascript - 用于匹配星号、波浪号、破折号和方括号的正则表达式

javascript - FineUploader onProgress() 回调不适用于 Android

javascript - 无法在 Mac 版 Firefox 中通过 Javascript 播放 wav 文件

javascript - 返回随机 JSON 对象

javascript - 将 JQuery 代码转换为其等效的 JavaScript 代码

javascript - 如何正确比较来自 ajax post call "data"的响应

javascript - 在 javascript 中创建一个 Json 对象

javascript - Jquery 提交表单然后重定向不起作用

javascript - 如何在ejs中包含javascript来检查数组中是否存在值

PHP+AJAX : How to make toggle for sorting data?