更新多个单独元素的JavaScript函数



我为标准复选框与ARIA复选框的示例编写了以下代码,并将CSS和JS包含在一个文件中,以便可以复制/粘贴。我已经有一段时间没有写JS了,我通过调用一个元素的id来获得我想要的函数。我有多个元素,我想更新函数以适用于每个元素。我知道这非常容易,但正如我所说,我已经有一段时间没有写JS了。我通过将ARIA属性包含到跨元素中来编写以下复选框。

<fieldset>
<legend id="check_title">ARIA Checkboxes</legend>
<p>Checkboxes using ARIA and JavaScript:</p>
<div role="application">
<div class="checkboxes" aria-labelledby="check_title">
<!-- The "aria-labelledby" attribute is required because label elements can only be applied to form elements. -->
<!-- We are using span elements instead of default HTML checkbox inputs so aria-labelledby is needed for association. -->
<span role="checkbox"  tabindex="0" aria-checked="false" aria-labelledby="labelA" id="optionA" onclick="toggleState();" onkeyup="ARIA_Checkbox_Key(event);">
<img src="unchecked.png" alt="" role="presentation" id="imageA">
<label id="labelA">Option A</label>
</span>
<br />
<span role="checkbox"  tabindex="0" aria-checked="false" aria-labelledby="labelB" id="optionB" onclick="toggleState();" onkeyup="ARIA_Checkbox_Key(event);">
<img src="unchecked.png" alt="" role="presentation" id="imageB">
<label id="labelB">Option B</label>
</span>
</div>
</div>
</fieldset>

然后,我使用以下JavaScript将aria-checked属性和图像从unchecked切换为checked:

<script type="text/javascript">
// This function binds the event keycode 32 (space bar) to run the function toggleState
// This is needed since the default functionality of a check box is triggered with the space bar
function ARIA_Checkbox_Key(event) { 
if(event.keyCode == 32) {
toggleState()
}
}  
// This function gets the aria-checked attribute of an element. If it is false, it makes it true and vice versa.
function toggleState() {
var getvalue=document.getElementById("optionA").getAttribute("aria-checked");
if (getvalue=="false") {
document.getElementById("optionA").setAttribute("aria-checked", "true");
document.getElementById("imageA").setAttribute("src", "checked.png");
} else {
document.getElementById("optionA").setAttribute("aria-checked", "false");
document.getElementById("imageA").setAttribute("src", "unchecked.png");
}
}
</script>

单击选项A或选项B的图像或标签将切换选项A的类和图像。这段代码目前有效,但我记不清了,而且我一辈子都不知道该用谷歌搜索什么,就是如何更新它来说明每个复选框。我认为我需要创建一个数组,然后引用数组中的正确点,但我不记得如何做到这一点。

您需要通过目标传递到函数:

onclick="toggleState(this);"
onkeyup="ARIA_Checkbox_Key(event);"

然后对于事件,使用事件目标:

function ARIA_Checkbox_Key(event) {
if (event.keyCode == 32) {
toggleState(event.target);
}
}

一旦目标元素通过,您就可以使用getElementsByTagName:获取子元素

function toggleState(el) {
var img = el.getElementsByTagName('img')[0],
getvalue = el.getAttribute("aria-checked");
if (getvalue == "false") {
console.log('toggleState', true);
el.setAttribute("aria-checked", "true");
img.setAttribute("src", "checked.png");
} else {
console.log('toggleState', false);
el.setAttribute("aria-checked", "false");
img.setAttribute("src", "unchecked.png");
}
}

最新更新