javascript - jQuery,每次单击都会在变量末尾添加一个递增的数字

标签 javascript jquery html function

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

<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]

这是我的 fiddle https://jsfiddle.net/k75fbvfs/5/

最佳答案

使用一个数组,并在点击处理程序外部定义它,以及迭代器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 .

关于javascript - jQuery,每次单击都会在变量末尾添加一个递增的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33995295/

相关文章:

javascript - 在 LazyLoad 之后在 OWL Carousel 上添加类

javascript - 如何让 nodejs 脚本成为 linux 中的 CLI 工具?

javascript - 无法在有限时间内执行脚本

html - CSS 在第 4 个 child 之后插入中断

用于定位 div ID 的 JavaScript 背景 slider

javascript - 响应式 fullpage.js : increase viewport to display full content

javascript - 表格行和单元格单击

jquery - Primefaces + jQuery + 三角形图标(不显示)!

javascript - for 循环在 firefox 中工作有问题吗?

html - CSS:为什么我的边框下方有间距?