简体   繁体   中英

JavaScript Module. Increment array on click

I am trying to understand JavaScript modules. As such I am using that pattern, or at least I think it is that pattern to cycle through an array on click.

Each click should display the next value in the array.

When the last value in the array has been reached and the click is registered again the cycle should start over.

The page will load, displaying the value at the start of the array.

For instance, the array contains ['green','yellow','red']

Page loads = value displayed is green

click = value displayed is yellow

click = value displayed is red

click = value displayed is green

and so on.

Here is a Fiddle of what I have so far: http://jsfiddle.net/TYj3p/

Here is the HTML:

<p>The color is <span id="print"></span>.</p>

Here is the JavaScript that I have but I am suck on the click part:

var s;
var ele;

Next = {

  settings : [
      {color : 'green'},
      {color : 'yellow'},
      {color : 'red'}
  ],

  elements : {
       span : $('#print')
  },

  init : function() {
      //kick things off
      s = this.settings;
      ele = this.elements;
      this.bindUIActions();
  },

  bindUIActions : function() {
      ele.span.ready(function() {
          Next.loadText();
      });
      ele.span.on('click', function() {
          Next.changeText();
      });
  },

  loadText : function() {
      ele.span.text(s[0].color);
  },

  changeText : function() {
      var i = 0;
      ele.span.text(s[i].color);
      i++;
  }

};

(function() {
    Next.init();
})();

Take a look at this demo: http://jsfiddle.net/TYj3p/7/

Add a button and call changeText on onClick method.

<button onclick="Next.changeText();">Click</button>

On you changeText function check the index of current color and if it is the last element show the first one. Your changeText function should be something like this:

changeText : function() {
    var index = Next.indexOfColor(ele.span.text());
    if(index < s.length-1) {
        ++index;
        ele.span.text(s[index].color);
    } else {
        ele.span.text(s[0].color);
    }
},

Add this function to return the index value of the current color.

indexOfColor: function (color) {
    for(var i=0; i < s.length; i++) {
       if(s[i].color == color) 
           return i; 
    }
    return -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