Native ways to achieve js tab switching style.

  Examples of a first share can not be achieved (since no block scope es5)

    for(var i=0; i<list.length; i++ )

      {

        list[i].onclick = function(){

            tabchange(i);

          }

      }

  solution:

    1.es6 new variable declaratively let (es6 have block-level scope, to solve the existing problems es5)

 

    for(let i=0; i<list.length; i++ )

      {

        list[i].onclick = function(){

            tabchange(i);

          }

      }

    2. The use of closure

    for(var i=0; i<list.length; i++ )

      {

        list[i].onclick = (function(){

            return function(){

            tabchange(i);

            }

          })(i);

      }

    3. Create the corresponding index for the element object

    for(var i=0; i<list.length; i++ )

      {

        list[i].myindex=i;

        list[i].onclick = function(){

            tabchange (this.myindex); // bind index corresponding to the elements

          }

      }

  // This approach generally used for carousel map, of course, is the framework would not consider so many questions  

Guess you like

Origin www.cnblogs.com/angle-xiu/p/11312247.html