如何在纯Javascript中的单选按钮上的addEventListener上使用? [英] How to use on addEventListener on radio button in Plain Javascript?
问题描述
如何在HTML中的单选按钮上附加事件监听器?考虑这种形式:
How can i attach event listener on a radio button in my html? Considering this form:
<label>
<input name="contract_duration" type="radio" value="6-Months" {{ $contract && $contract->contract_duration === '6-Months' ? 'checked' : '' }} />
<span>6-Months</span>
</label>
<label>
<input name="contract_duration" type="radio" value="1-Year" {{ $contract && $contract->contract_duration === '1-Year' ? 'checked' : '' }} />
<span>1-Year</span>
</label>
<label>
<input name="contract_duration" type="radio" value="2-Years" {{ $contract && $contract->contract_duration === '2-Years' ? 'checked' : '' }} />
<span>2-Years</span>
</label>
这是我的Javascript:
and this is my Javascript:
if(document.querySelector('input[name="contract_duration"]')){
document.querySelector('input[name="contract_duration"]').addEventListener("click", function(){
var item = document.querySelector('input[name="contract_duration"]').value;
console.log(item);
});
}
在执行期间,我的代码仅记录第一个,如果单击不显示任何内容,则为6-Months
其他代码.
during execution, my codes only log the first one, which is the 6-Months
others if click shows nothing.
推荐答案
querySelectorAll .这将返回所有匹配的元素-然后您可以遍历它们以向每个元素添加一个事件侦听器.
The querySelector function only returns the first element of all the ones matched by the selector - hence your problem. You need to use querySelectorAll instead. This will return all the matched elements - and then you can loop through them to add an event listener to each.
此外,在这种情况下,最佳实践是侦听更改"事件而不是点击"事件,因此,当用户单击已选择的广播时,它不会不必要地触发.
Also, best practice in this scenario would be to listen to the "change" event rather than "click", then it doesn't fire unnecessarily when the user clicks an already-selected radio.
演示:
if (document.querySelector('input[name="contract_duration"]')) {
document.querySelectorAll('input[name="contract_duration"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
var item = event.target.value;
console.log(item);
});
});
}
<label>
<input name="contract_duration" type="radio" value="6-Months" checked />
<span>6-Months</span>
</label>
<label>
<input name="contract_duration" type="radio" value="1-Year" />
<span>1-Year</span>
</label>
<label>
<input name="contract_duration" type="radio" value="2-Years" />
<span>2-Years</span>
</label>
这篇关于如何在纯Javascript中的单选按钮上的addEventListener上使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!