简体   繁体   English

JavaScript模块。 点击增加数组

[英]JavaScript Module. Increment array on click

I am trying to understand JavaScript modules. 我正在尝试了解JavaScript模块。 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'] 例如,数组包含['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/ 这是到目前为止我的小提琴: http : //jsfiddle.net/TYj3p/

Here is the HTML: 这是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: 这是我拥有的JavaScript,但我对点击部分很感兴趣:

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/ 看一下这个演示: http : //jsfiddle.net/TYj3p/7/

Add a button and call changeText on onClick method. 添加一个按钮,然后在onClick方法上调用changeText。

<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. 在您的changeText函数上,检查当前颜色的索引,如果它是最后一个元素,则显示第一个。 Your changeText function should be something like this: 您的changeText函数应如下所示:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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