javascript - 转换脚本以处理多个实例

标签 javascript jquery foreach

让我们看看这个脚本,它是一个简单的轮播

$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

我知道选项一应该再次重写,但是你们中有人看到一个可以使其可重用的快速修复吗?

一个 fiddle :https://jsfiddle.net/6z8n5pnq/ 多 fiddle :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 组件的上下文。稍微纠正了你的 fiddle 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);
        });
    },
}

关于javascript - 转换脚本以处理多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31188807/

相关文章:

javascript - 当iframe的源是javascript时浏览器做了什么

javascript - Chrome - 中断属性修改

jquery - 3D 圆柱体在小值上失去完整性

php - 如何在每个循环内将数组的值写入mysql表?

javascript - 在图片上方显示文字

javascript - 渲染 EJS 模板并将其保存为文件

javascript - 如何在 dropzone.js 中设置上传按钮

javascript - 无法让粘性页脚工作 - 尝试一切

php - 将数据数组从 android 传递到 php 文件不会进入数据库

C#、objectCollection.OfType<T>() 和 foreach(objectCollection 中的 T 项)、IEnumerable 到 IEnumerable<T>