如何解决类似表上的html和javascript
我正在学习有关Web开发的基础课程。我使用html创建了一个非常简单的表,其中包含2列:苹果和水果。水果的数量应为苹果的数量+ 5(更好地理解的基本方法)。我也尝试添加addeventlistener
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits = apples + 5;
fruits.innerHTML = fruits;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change',calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
我在“水果”列上没有得到“ 8”。我在代码中缺少什么吗?预先感谢
解决方法
var fruits = document.getElementById('fruits');
function calculate(event) {
//use event here to get the apples element value on every change event.target.value so you dont have to fetch the element every time
fruits.value = (parseInt(event.target.value) + 5);
//parse it as nummber and + 5
}
var inputElement = document.getElementById('apples');
inputElement.addEventListener('change',calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
在此处阅读如何target Event Property
还要阅读有关JavaScript parseInt() Function
的信息 ,- 输入值在
value
标签上的input
属性上更新。因此需要获得诸如fruits.value
和apple.value
之类的价值。 - 并且
apples.value
是字符串,因此对于求和运算,需要将其转换为数字。
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits.value = Number(apples.value) + 5;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change',calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
,
从➜ LINKED_LIST git:(master) ✗ clang linked_list.c && ./a.out
print list:
arg: 2
arg: 1
arg: 0
change arg:
print list:
arg: 42
arg: 42
arg: 42
while arg: 42
while arg: 42
while arg: 42
获取字符串值,并使用apples.value
转换为整数,然后更新结果。
parseInt
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits.value = parseInt(apples.value) + 5;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change',calculate);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。