gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:14:42 24 4
gpt4 key购买 nike

我正在通过我的原型(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com