<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />
基本上,这是我的 html。我现在想做的是使用 JavaScript,而不是 jQuery,在单击单选按钮时清除文本输入字段(如果之前输入过某些内容),并在有人单击文本字段时取消选中单选按钮。我很快找到了 jQuery 解决方案,但接到的任务是使用 JavaScript。由于我对 JS 没有太多经验,所以我无法全神贯注地让它工作。
有什么想法吗? 非常感谢。
最佳答案
您可以使用.querySelectorAll()和 .querySelector()为了找到元素和 .addEventListener()附加事件处理程序:
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.addEventListener('change', function(e) {
document.querySelector('#locationName').value = '';
});
});
document.querySelector('#locationName').addEventListener('input', function(e) {
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.checked=false;
});
})
<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />
关于javascript - 使用 Javascript 清除文本框和单选按钮 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52385672/