微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery 插件 .append .each 和一个 uniqe id

如何解决jquery 插件 .append .each 和一个 uniqe id

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

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

(function( $ ) {

    $.fn.plugin = function( options ) {

        this.each(function() {

            var keyFrames = "@keyframes animate {0%{transform:translate3d(0,0)}100%{transform:translate3d(-250px,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)}}";
            $("<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)}100%{transform:translate3d(-250px,0)}}";,您的问题是您有 counter++,但之后不要连接任何内容。您的代码应如下所示:

(function( $ ) {

    $.fn.plugin = function( options ) {

        this.each(function() {
            
            var counter = 1;
            
            var keyFrames = "@keyframes animate" + counter++ + " {0%{transform:translate3d(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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。