Deleting of an item, indexing problem...
for (var i = 0; i < max; i++) {
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(i, 1);
});
}
When i click on a button, a new table is added... i change some information in table and again add another table... and i delete this table... but the array value does delete the first index alone.
开发者_如何学运维The Value of i is always zero and it deletes the first item in the Array. How can i ensure that for each table it has different ID.
For each click i feel so that i value always starts from Zero....
You're overwriting the value of i
at each loop. You could use an anonymous function to pass the variable by value:
for (var i = 0; i < max; i++) {
(function(i){ //i is now defined within the scope of this anonymous function
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(i, 1);
}, true);
})(i); //Pass i to the anonymous function
}
Note that i
can have a different name inside the anonymous function, without making a difference.
ANother notice: Pass three arguments to addEventListener
, because many browsers will throw an error if the third argument is omitted.
Because i scope is outside event. You need get index from variable e, or maybe work this code:
for (var i = 0; i < max; i++) {
var ii = i;
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(ii, 1);
});
}
But I am not sure it works on javascript.
精彩评论