jQuery,每次点击都会在变量的末尾添加一个越来越多的数字

时间:2015-11-30 09:30:46

标签: javascript jquery html function

我正在通过我的原型创建一个新对象。单击一个元素我想创建一个同名的新对象,但添加一个每次增加到名称末尾的数字。这是我的代码:

<p class="clickMe">click me</p>

<script>
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

(".clickMe").click(function(event) {
 var i;
  if (i == 'undefined') { 
    i = 1;
  } else {
    i = i++;
  }
  var myFather[i] = new person("John", "Doe", 50, "blue"); 
  // so on click 2 the name would be : myFather2, then on click 3 myFather3 and so on..
 }
 </script>

这部分的正确语法是什么:

 myFather[i]

这是我的小提琴https://jsfiddle.net/k75fbvfs/5/

1 个答案:

答案 0 :(得分:1)

使用数组,并在点击处理程序外部定义它,以及迭代器i

function person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

var fathers = [],
    i = 0; // Start counting at 0

$(".clickMe").click(function(event) { // $ was missing
  fathers.push(new person("John", "Doe", 50, "blue"));
  console.log(fathers[i], i, fathers.length); // Also log `i`
  i++; // You don't need to assign `i`, `++` modifies the variable.
});
//^ missing `);`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="clickMe">click me</p>

这是一个updated fiddle