转换用于处理多个实例的脚本

Convert script for working with multiple instances

本文关键字:实例 脚本 用于 处理 转换      更新时间:2023-09-26

让我们看看这个脚本,它是一个简单的旋转

$script = {
   init: function(){
      this.heros(3000);
   },
   heros: function (time) {
        var t;
        var $hero = $('.hero');
        var $images = $('.hero > div');
        $hero.data('current', 0);
        var $bullets = $('<div>').addClass('bullets');
        for ( var i = 0; i<$images.length; i++ ) {
            var $item = $('<span>');
            $item.on('click', function () {
                clearTimeout(t);
                play( $(this).index() );
            });
            if(i==0) { $item.addClass('active') }
            $bullets.append( $item );
        }
        var play = function (current) {
            if(current==undefined) {
             current = $hero.data('current');
            }
            var nextMargin;
            if ( (current+1) == $images.length ) {
                nextMargin = 0  ;
                $hero.data('current',0);
            } else {
                nextMargin = (current + 1 )*100;
                $hero.data('current', (current + 1));
            }   
            $images.eq(0).css('marginLeft', -nextMargin + '%'); 
            $bullets.find('span').eq($hero.data('current')).addClass('active').siblings().removeClass('active');
            clearTimeout(t);
            t = setTimeout(play, time);
        }
        $hero.append($bullets);
        t = setTimeout(play, time);
    },
}

问题是它工作得很好,但前提是只有一个.hero元素。。如果有多个子弹混在一起,它不尊重.length

我知道第一个选项应该是再次重写,但你们中有人看到能让它重复使用的快速解决方案吗?

一把小提琴:https://jsfiddle.net/6z8n5pnq/多重小提琴:https://jsfiddle.net/6z8n5pnq/1/

-编辑-

我试过了:

定义在init上调用的上一个函数

preheros: function(time) {
        var self = this;
        $('.heros').each(function(){
            self.heros($(this), time);
        });
},

编辑英雄的开端:

heros: function ($hero, time) {
        var t;
        /*var $hero = $('.hero');*/
        var $images = $hero.find('>div');

但没有成功。。。

知道吗?

-编辑-

天啊,是$('.hero').each而不是$('.heros').each,它起作用了!

执行此操作的最简单方法是使用$(selector).each函数隔离每个.hero组件的上下文。稍微修正了你的小提琴https://jsfiddle.net/6z8n5pnq/2/
function apply($hero, time){
   var t;       
   var $images = $hero.children('div');
  //all your logic here...
}
$script = {
    init: function () {
        this.heros(3000);
    },
    heros: function (time) {
        $('.hero').each(function(){
            apply($(this), time);
        });
    },
}