我正在尝试创建一个简单的待办事项列表项目。当用户输入一个项目时,它将数据存储在数据结构中,该数据结构包含用于三种不同类型活动的三个数组。我在此行上不断收到错误消息“无法读取未定义的属性'replace'”:newHtml = html.replace('%activity%',obj.activity);尝试将html占位符文本替换为用户向UI添加新项目时输入的文本。
这是Javascript代码:
addListItem: function(obj, type) {
var html, newHtml;
//1. create HTML string with placeholder text
if (type === 'health') {
html = '<div class="item row" id="health-%id%"><p class="item_description">%activity%</p><p class="item_start">%start%</p><p class="until">until</p><p class="item_end">%end%</p><p class="item_percentage">5%</p><button class="delete_btn"><i class="ion-ios-close-outline"></i></button></div>';
} else if (type === 'work') {
html = '<div class="item row" id="work-%id%"><p class="item_description">%activity%</p><p class="item_start">%start%</p><p class="until">until</p><p class="item_end">%end%</p><p class="item_percentage">5%</p><button class="delete_btn"><i class="ion-ios-close-outline"></i></button></div>';
} else if (type === 'leisure') {
html = '<div class="item row" id="leisure-%id%"><p class="item_description">%activity%</p><p class="item_start">%start%</p><p class="until">until</p><p class="item_end">%end%</p><p class="item_percentage">5%</p><button class="delete_btn"><i class="ion-ios-close-outline"></i></button></div>';
}
// 2. replace placeholder with some actual text
newHtml = html.replace('%activity%', obj.activity);
newHtml = newHtml.replace('%id%', obj.id);
newHtml = newHtml.replace('%start%', obj.startTime);
newHtml = newHtml.replace('%end%', obj.endTime);
// 3. insert HTML into the DOM
document.querySelector(DOMstrings.list).insertAdjacentHTML('beforeend', newHtml);
},
活动文本最初是从此公共方法中获取的:
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value,
activity: document.querySelector(DOMstrings.inputActivity).value,
startTime: document.querySelector(DOMstrings.inputStart).value,
endTime: document.querySelector(DOMstrings.inputEnd).value
};
},
我试图使用断点调试代码,并且一直对if / else语句说'type is undefined'。
这是我调用addListItem函数(第3个)的方式:
// 1. get the field input data
var usersInput = UICtrl.getInput();
// 2. add item to the activity controller arrays
newItem = activityCtrl.addItem(usersInput.type, usersInput.activity, usersInput.startTime, usersInput.endTime);
// 3. add the new item(s) to the UI (into the correct position depending on what the time is)
UICtrl.addListItem(newItem);