簡體   English   中英

jquery 插件不起作用?

[英]jquery plugin doesn't work?

jquery 函數“.textAnim”什么都不做 textTyping_animation(); 工作正常,但 .textAnim 不起作用。 這是插件代碼:

function textTyping_animation(text,location,speed){
var progress = 0;
var a = setInterval(function(){
    progress++;
    document.getElementById(location).innerHTML = text.substring(0,progress);
    if(progress == text.length){
        clearInterval(a);
    }
},speed);
};
(function($){
$.fn.textAnim = function(text,speed){
    var progress = 0;
    var a = setInterval(function(){
        progress++;
        $(this).html(text.substring(0,progress));
        if(progress == text.length){
            clearInterval(a);
        }
    },speed);
};
})(jQuery);

這是執行:

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
});

html加載代碼:

<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script type="text/javascript" language="javascript" src="js/jqueryplugins.js" ></script>
<script type="text/javascript" language="javascript" src="js/libraries/gamelibrary.js"></script>

問題在於傳遞給setInterval()的回調函數中的this是窗口,而不是您想要的元素。 修改您的代碼以在textAnim()函數中保存對this的引用(它確實引用了正確的元素),然后在傳遞給setInterval()的回調中使用它:

(function($){
    $.fn.textAnim = function(text,speed){
        var progress = 0,
            element = this; // this will be the element in the jQuery object
        var a = setInterval(function(){
            progress++;
            $(element).html(text.substring(0,progress));
            if(progress == text.length){
                clearInterval(a);
            }
        },speed);
    };
})(jQuery);

這是一個更新的 DEMO

改變

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
});

成為

$(document).ready(function(){
starttext = function()
{
    document.getElementById("textbox").style.display = "block";
    //textTyping_animation("Dit is een dummy text!","textbox_inner",70);
        $("#textbox_inner").textAnim("Dit is een dummy text!",70);
}
starttext();
});

它應該可以工作;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM