我正在尝试将元素子文本推送到我的对象提醒,方法是将其传递给新的提醒方法,但它不会推送每个元素文本只是替换它们。
$(document).on('click', '.save-reminder-button', function() {
var value = $(this).siblings('input').val(); //get the value of input
var title = $(this).siblings('h1').text(value); //set the h1
var saveSetName = $(this).parent().siblings().children('input').val();
var elem = $(this).parent().parent().children(".reminder-lists").children(); //get the reminder-lists children
$(elem).each(function(i, e) {
var txt = $(e).text(); //set txt to the elem text node
saveSetName = new ReminderSet(saveSetName)
.add(new Reminder(txt)) //create new reminder to push to reminders array
});
})
var ReminderSet = function(name) {
this.name = name;
this.reminders = [];
}
ReminderSet.prototype.add = function(reminder) {
this.reminders.push(reminder);
console.log(this.name, this.reminders);
return this;
}
ReminderSet.prototype.list = function() {
console.log(this.reminders);
}
var Reminder = function(description) {
this.description = description;
}
答案 0 :(得分:0)
在代码中,为每个推送元素创建一个ReminderSet对象。创建一次对象。像这样,
$(document).on('click', '.save-reminder-button', function() {
var value = $(this).siblings('input').val(); //get the value of input
var title = $(this).siblings('h1').text(value); //set the h1
var saveSetName = $(this).parent().siblings().children('input').val();
var elem = $(this).parent().parent().children(".reminder-lists").children(); //get the reminder-lists children
saveSetName = new ReminderSet(saveSetName);
$(elem).each(function(i, e) {
var txt = $(e).text(); //set txt to the elem text node
saveSetName.add(new Reminder(txt)) //create new reminder to push to reminders array
});
})
答案 1 :(得分:0)
这一行:
saveSetName = new ReminderSet(saveSetName)
.add(new Reminder(txt))
你只是用旧值替换旧对象的值,为了使它按照你想要的方式工作,你必须在for
循环之外声明一个新变量:
var reminderSet = new ReminderSet(saveSetName);
一旦你进入你的循环,你就可以添加你的提醒:
$(elem).each(function(i, e) {
var txt = $(e).text(); //set txt to the elem text node
reminderSet.add(new Reminder(txt))
});