[英]How can I remove a specific element from my array generated by a blaze helper?
I have a helper class that pushes an element into an array when a checkbox is checked and should remove the element when it is unchecked. 我有一个帮助器类,当选中一个复选框时,该元素将元素推送到数组中;而当未选中该元素时,应删除该元素。 I am able to successfully push the element to the array but having trouble removing it. 我能够成功将元素推送到数组,但无法删除它。
I am noticing some curious behavior. 我注意到一些奇怪的行为。 For instance, unchecking the element also pushes it to the array making a duplicated of it instead of removing it from the array. 例如,取消选中该元素还会将其推入数组以使其重复,而不是将其从数组中删除。 If I console log the index value, I get -1 for each array element that I'm trying to remove. 如果控制台记录索引值,则我要删除的每个数组元素都为-1。
Here is the Blaze Code: 这是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
searches for an element itself and will not be able to match an object by its instruction
property. indexOf
搜索元素本身,并且将无法通过其instruction
属性匹配对象。 You should instead use a for-loop to iterate over your checkedJobs
array and compare each instruction
to currentId
in order to find the correct index. 相反,您应该使用for循环遍历您的checkedJobs
数组,并将每条instruction
与currentId
进行比较,以找到正确的索引。 Replace the contents of your else
block with the following: 用以下内容替换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.