简体   繁体   中英

Multiple functions wrapped in .each(function() - jQuery

Trying to turn multiple functions into one .each function in jQuery, but getting blank page. Any idea what I'm missing?

This code is functioning properly:

    new Vivus('svg-0', {duration: 200}, function(){
        $('.svg-animation .svg-1').css( "opacity", "0");
        $('.svg-animation .illustration-1').css( "opacity", "1");
    });

    new Vivus('svg-1', {duration: 200}, function(){
        $('.svg-animation .svg-2').css( "opacity", "0");
        $('.svg-animation .illustration-2').css( "opacity", "1");
    });


    new Vivus('svg-2', {duration: 200}, function(){
        $('.svg-animation .svg-3').css( "opacity", "0");
        $('.svg-animation .illustration-3').css( "opacity", "1");
    });

    new Vivus('svg-3', {duration: 200}, function(){
        $('.svg-animation .svg-4').css( "opacity", "0");
        $('.svg-animation .illustration-4').css( "opacity", "1");
    });

Here's the each function I'm trying to build:

$('.drawings').each(function (index, value) {
    var svgs = ($(this).find('#svg-' + index));
    //console.log(svgs);

    new Vivus(svgs, {duration: 200}, function(){
        $('.svg-animation .svg-' + index).css( "opacity", "0");
        $('.svg-animation .illustration-' + index).css( "opacity", "1");
    }); 
});

Here's HTML if needed...the brackets are code used in ExpressionEngine:

<div class="svg-animation">
    <div class="drawings mac">
       <svg id="svg-{blocks:index:of:type}" class="svg svg-{blocks:index:of:type}" style="max-width: {svg_max_width}" xmlns="http://www.w3.org/2000/svg" viewBox="{svg_view_box}">
            <title>{svg_title}</title>
            {svg_code}
        </svg>
        <img class="illustration illustration-{blocks:index:of:type}" style="max-width: {svg_max_width}" src="/assets/src_assets/images/step-1-img.png">
    </div>
</div>

This should work.

for (var i=0; i<4; i++) {
    new Vivus('svg-'+i, {duration: 200}, function(){
        $('.svg-animation .svg-'+(i+1)).css( "opacity", "0");
        $('.svg-animation .illustration-'+(i+1)).css( "opacity", "1");
    });
}

Otherwise, based upon your markup snippet, here is a dynamic variant:

$('.drawings .svg').each( function() {

    var theID = $(this).attr('id').replace("svg-", "");
    var nextID = theID + 1;


    new Vivus('svg-'+theID, {duration: 200}, function(){
        $('.svg-animation .svg-'+ nextID).css( "opacity", "0");
        $('.svg-animation .illustration-'+ nextID).css( "opacity", "1");
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM