javascript新手......
我正在尝试构建一个事件处理程序,它会在单击时将一组链接的tabIndex设置为0 ...我不确定如何准确定位。
示例:
<div id="a">Link</div>
<div id="b">
<div class="link" tabIndex="-1">Link 1</div>
<div class="link" tabIndex="-1">Link 2</div>
<div class="link" tabIndex="-1">Link 3</div>
</div>
当我点击#a时,我正在查看如何使用#b中的“link”类来定位所有div。
任何建议都赞赏!!
答案 0 :(得分:1)
除了已经给出的答案,我建议使用更有意义的标记,如果可行/可能,利用现代DOM。
function nullifyTabIndex(elmNode) {
elmNode.setAttribute('tabindex', 0);
}
function handleNullifyTabIndices(evt) {
var
tabItemList = document.body.querySelectorAll('#b > li');
tabItemList.forEach(nullifyTabIndex);
}
function registerHandlingOfTabindexChange(evt) {
var
elmTrigger = document.body.querySelector('#a');
elmTrigger.addEventListener('click', handleNullifyTabIndices, false);
}
document.addEventListener('DOMContentLoaded', registerHandlingOfTabindexChange, false);
&#13;
<a href="#" id="a">Trigger Tab Index Change</a>
<nav>
<ul id="b">
<li tabindex="-1"><a href="#">Link 1</a></li>
<li tabindex="-1"><a href="#">Link 2</a></li>
<li tabindex="-1"><a href="#">Link 3</a></li>
</ul>
</nav>
&#13;
答案 1 :(得分:0)
以下内容可以为您提供帮助。
HTML:
<div id="a">Link</div>
<div id="b">
<div class="link" tabIndex="-1">Link 1</div>
<div class="link" tabIndex="-1">Link 2</div>
<div class="link" tabIndex="-1">Link 3</div>
</div>
JS:
<script>
window.onload = function () { test() }; //Call the test function below on load
function test() {
document.getElementById("a").addEventListener("click", updateAttribute); //attach event listener to div with id "a"
}
function updateAttribute()
{
var ele = document.getElementsByClassName("link"); //Get all div elements with class name "link" under div "b"
for(var i = 0; i < ele.length; i++) //Loop through all div elements and set attribute "tabIndex" to "0"
ele[i].setAttribute("tabIndex", "0");
}
</script>