我的 HTML 看起来像这样:
<div class="panel">
<div class="panel-heading"></div>
<div class="panel-body"></div>
</div>
我目前正在选择 panel-heading
元素的父节点,如下所示:
e.target.parentNode
这给我留下了 panel
类。一切顺利。
但现在我想在那个时候获取 panel-body
。不幸的是,这样做是行不通的:
e.target.parentNode.querySelector('.panel-body')
在普通 javascript 中有没有一种干净的方法来做到这一点?
最佳答案
如果你知道节点的类,你总是可以使用document
对象:
var tgt = document.querySelector('.panel-body');
如果需要在点击等事件的上下文中获取节点,可以委托(delegate)。
- Find node that is an ancestor of all of the nodes you wish to access.
- ex.
.panel
- Register the event on that node.
- ex.
panel.addEventListener('click', callback)
- During the bubbling phase, find the
event.target
by comparing it to theevent.currentTarget
(the node that is registered to the event)
- ex.
if(e.target !== e.currentTarget) {...
点击节点,会显示它的标签和类。 细节在片段中注释
片段
// Reference top element
var panel = document.querySelector('.panel');
// Register .panel on click event
panel.addEventListener('click', highlight);
function highlight(e) {
// if the clicked node is not .panel
if (e.target !== e.currentTarget) {
// Get the clicked node's class
var tgtClass = e.target.className;
// Get the clicked node's tag
var tgtTag = e.target.tagName;
}
/* Set the clicked node's tag and class
|| as it's content.
*/
e.target.textContent += ' ' + tgtTag + '.' + tgtClass;
}
[class*=panel] {
border: 1px dashed blue;
color: red;
}
<section class="panel">
<hgroup class='panel-heading-group'>
<h1 class="panel-heading">HEADING</h1>
<h2 class='panel-sub-heading'>SUB-HEADING</h2>
</hgroup>
<main class="panel-body">
<p>CONTENT A</p>
<p>CONTENT B</p>
</main>
<footer class='panel-footer'>FOOTER</footer>
</section>
关于javascript - 链接 Vanilla javascript 遍历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43586180/