我在下面的表格中有2个数据。我试图得到选定的变量值(让input1 &让input2)在通过模板字符串变量let message
提交时出现的消息中显示,但它不工作。我没有得到任何错误。
知道为什么不工作吗?事件监听器是否可以简化,这样我就不必为每个监听器写一个新变量,因为我有4个数据器?
const victory = document.createElement('audio'),
form = document.querySelector('form'),
nameInput = document.querySelector('#name-input'),
surnameInput = document.querySelector('#surname-input'),
footer = document.querySelector('#footer');
const messageBox = document.createElement('div');
messageBox.setAttribute('class', 'message-box');
victory.src = 'sound/victory.mp3';
let input1 = nameInput.addEventListener('input', () => {
const nameValue = surnameInput.value;
});
let input2 = surnameInput.addEventListener('input', () => {
const surnameValue = surnameInput.value;
});
form.addEventListener('submit', (e) => {
e.preventDefault();
let message = `You have succesfully ordered ${input1} ${input2}`;
messageBox.appendChild(document.createTextNode(message));
victory.play();
footer.parentNode.insertBefore(messageBox, footer);
messageBox.style.backgroundColor = 'green';
messageBox.style.textAlign = 'center';
messageBox.style.margin = '0 1rem 2rem';
messageBox.style.padding = '1rem';
messageBox.style.borderRadius = '5px';
});
<form action="">
<fieldset>
<legend>Choose your skater</legend>
<div>
<label>Name</label>
</div>
<div>
<input id="name-input" list="name" type="text" title="Select desired name of your skater">
<datalist id="name">
<option value="Tony" data-id="1"></option>
<option value="Joe" data-id="2"></option>
<option value="Paul" data-id="3"></option>
<option value="Scott" data-id="4"></option>
</datalist>
</div>
<div>
<label>Surname</label>
</div>
<div>
<input id="surname-input" list="surname" type="text" title="Select desired surname of your skater">
<datalist id="surname">
<option value="Hawk" data-id="1" label="james"></option>
<option value="Carter" data-id="2"></option>
<option value="Philmore" data-id="3"></option>
<option value="Venice" data-id="4"></option>
</datalist>
</div>
</fieldset>
<button class="btn" type="submit" title="Submit your choice">Submit</button>
</form>
<footer id="footer"></footer>
您捕获输入值的方式是错误的。
let input1 = '';
nameInput.addEventListener('input', () => {
input1 = nameInput.value;
});
let input2 = '';
surnameInput.addEventListener('input', () => {
input2 = surnameInput.value;
});