所以..我想在输入中显示一个,当我选择 1 时,是否可以不使用Javascript?
代码:
<div class="col-sm-12">
<div class="form-group">
<input list="browsers" class="form-control step1" name="test" id="test" />
<datalist id="browsers">
<option data-value="ONE">1</option>
<option data-value="TWO">2</option>
</datalist>
</div>
</div>
答案 0 :(得分:1)
没有JavaScript,您将无法做到。但这是 JS的示例。
// Grab the options from the datalist
const options = document.querySelectorAll('datalist option');
// Create a dictionary object that maps
// the data value against the textContent
// { 1: 'ONE', 2: 'TWO' }
const mapped = [...options].reduce((acc, c) => {
acc[c.textContent] = c.dataset.value;
return acc;
}, {});
// Grab the input and add a select handler
const input = document.querySelector('#test');
input.addEventListener('select', handleChange, false);
function handleChange(e) {
// Change the input value to the value in the dictionary
// based on the value of the selected option. `Object.key` ensures that
// the input is one of the keys in the mapped object otherwise you'll
// get errors
if (Object.keys(mapped).includes(input.value)) input.value = mapped[e.target.value];
}
<div class="col-sm-12">
<div class="form-group">
<input list="browsers" class="form-control step1" name="test" id="test" />
<datalist id="browsers">
<option data-value="ONE">1</option>
<option data-value="TWO">2</option>
</datalist>
</div>
</div>