使用单选按钮组上的数据属性来显示文本



我想要的结果是,当用户将键盘焦点发送到单选按钮组,并使用箭头键导航到每个单选按钮,或者使用定点设备(鼠标(单击单选按钮时,该单选按钮的数据属性值设置为元素(h2(。

我已经走了这么远,现在被卡住了。我使用ID作为示例,但是,我更喜欢使用类或数据集=";X〃;。

下面的代码设置第一个数据列值,但不设置第二个。

感谢您的帮助,因为我从Stackoverflow中学到了很多。对不起,我需要香草JS而不是jQuery。

<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" data-set="Green" id="demo3">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" data-set="Blue" id="demo3">
</label>
</p>
<h2 id="chjkl"></h2>
document.getElementById('demo3').onclick = function changeClk() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}
document.getElementById('demo3').onfocus = function changeFoc() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}

使用event.target获取数据集。

在下面的示例中,我更改了h2元素背景的颜色。请注意,我正在将event传递到函数中,并在eventListener中调用函数。

此外,我没有两个eventListeners,而是在单选按钮中添加了一个,然后使用querySelectorAll()进行查询。然后通过循环运行nodeList,并在eventListener启动时检查event.target

代码的一个问题是,有多个元素具有相同的ID。不应有多个具有任何唯一ID的元素。ID只能对一个元素唯一。

let radio = document.querySelectorAll('.radio')
let target = document.getElementById('chjkl')
function changeColor(e) {
target.style.backgroundColor = e.target.dataset.col
target.textContent = e.target.dataset.col
}
radio.forEach(btn => {
btn.addEventListener('focus', changeColor)
})
#chjkl {
display: flex;
justify-content: center;
letter-spacing: 1.3rem;
}
<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" class="radio">
</label>
<label for="">The colour is Red
<input type="radio" name="bob" data-col="Red" class="radio">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" class="radio">
</label>
<label for="">The colour is Orange
<input type="radio" name="bob" data-col="Orange" class="radio">
</label>
</p>
<h2 id="chjkl"></h2>

最新更新