[英]How can I remove a specific element from my array generated by a blaze helper?
我有一個幫助器類,當選中一個復選框時,該元素將元素推送到數組中;而當未選中該元素時,應刪除該元素。 我能夠成功將元素推送到數組,但無法刪除它。
我注意到一些奇怪的行為。 例如,取消選中該元素還會將其推入數組以使其重復,而不是將其從數組中刪除。 如果控制台記錄索引值,則我要刪除的每個數組元素都為-1。
這是Blaze代碼:
Template.Job_setup_page.onCreated(function homePageOnCreated() {
this.checkedJobs = [];
});
Template.Job_setup_page.events({
'click .filled-in'(event, instance) {
var currentId = event.target.id;
if($(".filled-in").is(':checked')){
instance.checkedJobs.push({
instruction: currentId,
quantity: 1
})
}
else {
var index = instance.checkedJobs.indexOf(currentId);
instance.checkedJobs.splice(index, 1);
console.log("This is the current Id", currentId);
console.log("this is the index", index);
};
},
});
indexOf
搜索元素本身,並且將無法通過其instruction
屬性匹配對象。 相反,您應該使用for循環遍歷您的checkedJobs
數組,並將每條instruction
與currentId
進行比較,以找到正確的索引。 用以下內容替換else
塊的內容:
var jobs = instance.checkedJobs
for (var i = 0; i < jobs.length; i++) {
if (jobs[i].instruction === currentId) {
instance.checkedJobs.splice(i, 1)
console.log('currentId:', currentId)
console.log('index:', i)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.