将一个函数作为参数传递给另一个函数,每次调用函数时检查返回值

pass a function as argument to another function, check for return value each time calling a function

本文关键字:函数 另一个 调用 返回值 检查 参数传递 一个      更新时间:2023-09-26

我有一个每次返回不同值的函数:

this.imageArr = [ "1.png", "2.png" ]
this.changeImg = function () {
    return $( "#Img" ).attr("src", "images/" + this.imageArr[Math.floor(Math.random()*this.imageArr.length)]);
}

这个函数每次被调用时都会随机改变图像的 src。

现在,我有第二个功能可以管理多个动画

$.fn.animationNSteps = function ( className, delay, steps, infinite, visibility, func ) {
      [...]
      $(this).animationNSteps( className, delay, steps, infinite, visibility, func )
}

最后一个参数是"func"。如果给定(有时给定,有时不给定),它应该使用以前的函数changeImg()随机更改图片。不幸的是,如果我这样称呼它:

$("#title").animationNSteps ( class, 3000, 3, true, true, obj.changeImg )

它随机拍摄第一个电话的照片,但下一个和所有其他电话仍然相同。如何每次调用changeImg()函数来更改图像?

试试这个:

$("#title").animationNSteps ( 
    class, 3000, 3, true, true, 
    function(){
        return obj.changeImg();
    } )