简体   繁体   中英

How I can decrease and make better my ugly JavaScript code?

I tried to use $(this).next() to give control to closest siblings. But in this scope next sibling hasn't seen. If I use .each() function, the action apply to all elements in array, but they executed at the same time. I want see each animation are played, after another animation has done. I thinking to use .on() and .trigger() functions but I don't have ideas how I can implement them.

$('h1.main-logo-text').show().letterfx({
    "fx":"grow",
    "element_end":"destroy",
    "backwards":false,
    "timing":100,
    "fx_duration":"1000ms",
    onElementComplete: function(){
        $('#logoText1').show().letterfx({
            "fx":"grow",
            "element_end":"destroy",
            "backwards":false,
            "timing":100,
            "fx_duration":"1000ms",
            onElementComplete: function(){
                $('#logoText2').show().letterfx({
                    "fx":"grow",
                    "element_end":"destroy",
                    "backwards":false,
                    "timing":100,
                    "fx_duration":"1000ms",
                    onElementComplete: function(){
                        $('#logoText3').show().letterfx({
                            "fx":"grow",
                            "backwards":false,
                            "timing":100,
                            "fx_duration":"1000ms",
                        });
                    }
                });
            }
        });
    }
});

You could define a single function to call for each element; use .queue() , .promise() to perform next animation when previous animation is complete

var elems = ["h1.main-logo-text", "#logoText1", "#logoText2", "#logoText3"];

function fx() {
  return this.show().letterfx({
    "fx":"grow",
    "element_end":"destroy",
    "backwards":false,
    "timing":100,
    "fx_duration":"1000ms"
  }).promise("fx")
}

$({}).queue("_fx", $.map(elems, function(el) {
  return function(next) {
    fx.call($(el)).then(next)
  }
})).dequeue("_fx").promise("_fx")
.then(function() {
  console.log("complete")
})

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