[英]Updating JavaScript function for multiple individual elements
我为标准复选框与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属性和图像从未选中状态切换为选中状态:
<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的类和图像。此代码当前有效,但我不记得了,我一生也无法弄清楚如何更新Google以此来说明每个复选框。 我相信我需要创建一个数组,然后引用该数组中的正确点,但是我不记得如何做到这一点。
您需要将目标传递给功能:
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.