gpt4 book ai didi

javascript - 取id值

转载 作者:行者123 更新时间:2023-12-03 08:20:08 25 4
gpt4 key购买 nike

我想获取下面内容的id值?

<form id="mainForm"  name="mainForm">
<input type="radio" id="4" name="rads" value="1" checked>
<input type="radio" id="3" name="rads" value="2" />
<input type="radio" id="2" name="rads" value="3" />
<input type="radio" id="1" name="rads" value="4" />
</form>
<span id="result"></span>
<span id="test"></span>

<script>
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.getElementsById('id');
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}
</script>

您选择的值:1您选择的 ID:4

最佳答案

你应该这样做

document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.querySelector('[name="rads"]:checked').id;
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}

您需要使用 document.querySelector('[name="rads"]:checked') 选择选中的元素,然后使用 .id 获取 id

关于javascript - 取id值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33782404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com