2017-10-17 23 views
0

我試圖將一個元素的子文本傳遞給我的對象提醒,方法是將它傳遞給新的提醒方法,但不會推送每個只替換它們的元素文本。推新對象替換以前的對象

$(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

'new ReminderSet'創建一個空數組的新對象。您需要保存原始的並使用它。 – Will

回答

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 

    }); 

}) 
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)) 
});