我具有以下功能,当仅旋转图像的一个实例时,该功能可以正常工作:

// Next Angle Variable
nextAngle = 0;

$( ".portfolioDropLink" ).click(function() {

    // Icon Variable
    var currentIcon = $(this).find(".fa-angle-down");

    // Rotate Icon
    currentIcon.rotate(getNextAngle());

    function getNextAngle() {
        nextAngle += 180;
        if(nextAngle >= 360) {
            nextAngle = 0;
        }
        return nextAngle;
    }

});


当存在.portfolioDropLink类的两个实例时,nextAngle变量发生冲突,如何防止这种情况发生?

最佳答案

一种解决方案是retrieve the angle by getting its CSS value

另一种解决方案是将角度与元素的数据一起存储:

$( ".portfolioDropLink" ).click(function() {

    // Icon Variable
    var currentIcon = $(this).find(".fa-angle-down");

    // Rotate Icon
    currentIcon.rotate(getNextAngle(this));

    function getNextAngle(el) {
        //Get Value and Parse
        var currentAngle = el.getAttribute('data-angle');
        if (parseInt(currentAngle) == NaN) currentAngle = 0;

        //Get Next Value
        nextAngle =  parseInt(currentAngle) + 180;
        if(nextAngle >= 360) {
            nextAngle = 0;
        }

        //Set Value and Return
        el.setAttribute('data-angle', nextAngle)
        return nextAngle;
    }

});

09-20 21:07