访问不带id的DOM元素 [英] Accessing DOM elements without id
问题描述
我有一个大约500 div的页面,如下所示.
i have a page around 500 div as below.
<div onclick='test()' class='test>
<ul class='innermenu'>
<li>1</li>
.....
</ul>
</div>
当调用测试函数时,它需要隐藏调用该函数的菜单(内部菜单).
when the test function is called it need to hide the menu (innermenu) who calls that function.
我的问题是
-
不使用id即可唯一标识div
uniquely identify the div without using id
如何仅单独隐藏特定的ul.
How to hide only the particular ul alone.
推荐答案
好的,首先是快速修复,尽管这不是在页面上使用JS的最佳方法:
OK, first the quick fix, though it is not the best way to use JS on your page:
将呼叫更改为此:
<div onclick="test(this);" class="test">
然后在测试中使用此:
function test(el){
var uls = el.getElementsByTagName('ul');
for(var i = 0; i < uls.length; i++){
if(uls[i].className == 'innermenu'){
uls[i].style.display = "none";
break;
}
}
}
这将仅隐藏被单击的 div
的子 ul
.
This will hide just the child ul
of the div
that is clicked.
更好的方法
好的,答案更长.使用 attachEvent
和 addEventListener
在事件发生后附加事件,或使用jQuery之类的库来帮助您.这是原始解决方案:
OK, for the longer answer. Either attach the events after the fact using attachEvent
and addEventListener
or use a library like jQuery to help you out. Here is the raw solution:
以这种方式设置HTML(无需 onclick
):
Set up your HTML this way (no onclick
):
<div class="test">
然后在HTML的末尾添加以下内容:
And then at the very end of your HTML put this:
<script type="text/javascript">
var divs = document.getElementsByTagName('div');
function test(){
var uls = this.getElementsByTagName('ul');
for(var i = 0; i < uls.length; i++){
if(uls[i].className == 'innermenu'){
uls[i].style.display = "none";
break;
}
}
};
for(var i = 0; i < divs.length; i++){
var div = divs[i];
if(div.className !== "test") continue;
if(window.addEventListener){
div.addEventListener( 'click', test, true ); //FF, Webkit, etc
} else if (window.attachEvent) {
div.attachEvent('onclick', test); // IE
} else {
div.onclick = test; // Fallback
}
}
</script>
现在,您的HTML中没有JavaScript代码,您可以摆脱 test
函数上的多余参数.
Now, you don't have JavaScript code in your HTML, and you can get rid of the extra parameter on the test
function.
这篇关于访问不带id的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!