【问题标题】:jquery plugin .append .each and a uniqe idjquery 插件 .append .each 和一个唯一的 id
【发布时间】:2021-08-28 20:59:17
【问题描述】:

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

下面的代码在 header 属性中添加了每个 style 标签。 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>

【问题讨论】:

  • 应该是counter++ +"...

标签: jquery each


【解决方案1】:

当您运行代码时,您会看到 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>

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 2016-06-12
    • 2014-09-10
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多