遵循我的代码:
<div onclick="/*Here I would like to select the child element with the class 'vxf'*/">
<div class="abc"></div>
<div class="cir"></div>
<!--... other elements-->
<div class="vxf"></div>
<!--... other elements-->
</div>
<div onclick="/*Here I would like to select the child element with the class 'vxf'*/">
<div class="abc"></div>
<div class="cir"></div>
<!--... other elements-->
<div class="vxf"></div>
<!--... other elements-->
</div>
Run Code Online (Sandbox Code Playgroud)
如何使用纯javascript类"vxf"选择子元素?
T.J*_*der 16
传递this到您的处理程序...
onclick="clickHandler(this)"
Run Code Online (Sandbox Code Playgroud)
...然后为了获得最大的浏览器兼容性,只需查看子节点:
function clickHandler(element) {
var child;
for (child = element.firstNode; child; child = child.nextSibling) {
if (child.className && child.className.match(/\bvxf\b/)) {
break; // Found it
}
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
(或者,如果你想要所有匹配的孩子,请继续循环并构建一个数组.)
在大多数现代浏览器中,另一种选择是使用querySelector(查找第一个)或querySelectorAll(获取列表)匹配的子元素.可悲的是,这需要一些技巧:
function clickHandler(element) {
var child, needsId;
needsId = !element.id;
if (needsId) {
element.id = "TEMPID____" + (new Date()).getTime();
}
child = document.querySelector("#" + element.id + " > .vxf");
if (needsId) {
element.id = "";
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我们必须玩id游戏,因为我们只想要直接的孩子(而不是后代),不幸的是你不能在没有东西的情况下使用儿童组合器(因此element.querySelector("> .vxf");不起作用).
如果你不关心它是直接的孩子还是后代,那么当然它更容易:
function clickHandler(element) {
var child = element.querySelector(".vxf");
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14173 次 |
| 最近记录: |