我正在用JS构建一个简单的预算应用程序。现在,我能够成功输入费用或收入并将其显示在UI中。但是,不会显示说明,而是显示占位符文本。 。有人知道为什么吗?
下面是UI控制器。我创建了一个带有占位符文本的HTML字符串。接下来,我试图用一些实际数据替换占位符文本,在这种情况下,这是费用的描述。然后,我尝试将HTML插入dom。
var UIController = (function(){
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list'
};
return {
getInput: function(){
return {
type: document.querySelector(DOMstrings.inputType).value, //Will be either inc (income) or exp (expense)
description: document.querySelector(DOMstrings.inputDescription).value,
value: document.querySelector(DOMstrings.inputValue).value
};
},
addListItem: function(obj, type){
var html, newHtml, element;
//create HTML string with some placeholder text
if (type === 'inc'){
element = DOMstrings.incomeContainer;
html = `<div class="item clearfix" id="income-%id%"> <div class="item__description">%description%</div>
<div class="right clearfix"> <div class="item__value">%value%</div> <div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button> </div></div></div>`;
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;
html = `<div class="item clearfix" id="expense-%id%"> <div class="item__description">%description%</div>
<div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div>
<div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div></div></div>`;
}
//replace the placeholder text with actual data
newHtml = html.replace('%id%', obj.id);
newHtml = html.replace('%description%', obj.description);
newHtml = html.replace('%value%', obj.value);
//Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
getDOMstrings: function(){
return DOMstrings;
}
}
})();
答案 0 :(得分:0)
问题似乎在于您正在html
上进行每个文本替换,并将其保存到newHtml
,从而覆盖了先前的替换。只有您的%value%
替换才会生效。您需要使用newHtml
来构建替换内容:
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', obj.value);