jquery 插件 .append .each 和一个唯一的 id

jquery plugin .append .each and a uniqe id

我正在尝试创建一个简单的插件

下面的代码在 header 属性中添加了每个 style 标签。样式标签包含 CSS 动画,动画名称为 animate

(function( $ ) {

    $.fn.plugin = function( options ) {

        this.each(function() {

            var keyFrames = "@keyframes animate {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
            $("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
        });
        return this;
    };
}( jQuery ));

$( ".animation" ).plugin({});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 
</head>
<div class="animation">dsdsd</div>
</body>
</html>

但每次添加不同的动画名称时,我都会尝试这样做。例如... 这行不通

(function( $ ) {

    $.fn.plugin = function( options ) {

        this.each(function() {
            
            var counter = 1;
            
            var keyFrames = "@keyframes animate" + counter++ " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
            $("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
        });
        return this;
    };
}( jQuery ));

$( ".animation" ).plugin({});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 
</head>
<div class="animation">dsdsd</div>
</body>
</html>

当您 运行 您的代码时,您会看到 Uncaught SyntaxError: Unexpected string. 这是您实际查找位置的第一个线索(您使用字符串的某个地方)。

如果您查看此行:var keyFrames = "@keyframes animate" + counter++ " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";,您的问题是您有 counter++ 但之后不要连接任何内容。您的代码应如下所示:

(function( $ ) {

    $.fn.plugin = function( options ) {

        this.each(function() {
            
            var counter = 1;
            
            var keyFrames = "@keyframes animate" + counter++ + " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
            $("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
        });
        return this;
    };
}( jQuery ));

$( ".animation" ).plugin({});
<html> 
<body> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <div class="animation">dsdsd</div> </body> </html>