【发布时间】:2023-02-09 18:09:18
【问题描述】:
我正在尝试在另一个函数的对象中添加选中的单选按钮的值。 但是,没有添加任何内容,也没有返回错误。
我正在构建一个费用跟踪器并添加这些值(收入或费用)在我的计算中很重要。
Nb:当我尝试在捕获选中值的函数中使用 console.log 时,它工作得很好,但是当我尝试将该值添加到另一个函数中的数组对象时,没有添加任何内容。
const TransactionType = document.getElementsByName('selector');
addbtn.addEventListener('click', function() {
if (expense.value == '' || amount.value == '' || date.value == '') {
alert('Please fill all the fields!!!');
return;
} else {
const userExpense = {
id: generateID(),
type: getTransactionType(), // here is the problem nothing is added
date: date.value,
expense: expense.value,
amount: amount.value
};
userInput.push(userExpense);
localStorage.setItem('data', JSON.stringify(userInput));
location.reload();
}
});
function getTransactionType() {
TransactionType.forEach(item => {
if (item.checked) {
return item.value;
}
});
}
<!-- radio buttons to choose the type of transaction -->
<div class="container">
<h3>Select the type of transaction:</h3>
<ul>
<li>
<input type="radio" id="type-income" name="selector" value="income">
<label for="type-income">Income</label>
</li>
<li>
<input type="radio" id="type-expense" name="selector" value="expense">
<label for="type-expense">Expense</label>
</li>
<!-- <button onclick=" getTransactionType()">see value</button> -->
</ul>
</div>
【问题讨论】:
-
1.代码不完整。没有 addbtn,也没有显示 localStorage 2 的处理。我想制作一个 sn-p,但您使用的是此处不支持的 localStorage。无论如何,你为什么要重新加载页面?完全没有必要!
-
TransactionType.forEach(item => { if (item.checked) { return item.value; } });什么都不做。 return 语句在 forEach 中没有意义。你可能打算使用这个:const getTransactionType = () => document.querySelectorAll('[name=selector]:checked')[0].value;