如何通过单击按钮从JS中的多个类访问特定的一个类

问题描述 投票:0回答:1

我对如何从JavaScript中的多个类名访问一个元素有一定的疑问。例如,这是我的代码。

<html>
<head><title>Check</title>
</head>
<body>
<div class="div"><button type ="submit">a</button></div>
<div class="div"><button type ="submit">b</button></div>
<div class="div"><button type ="submit">c</button></div>
</body>
</html>

当我单击b的按钮时,我希望选择第二个div类。有人可以帮我解决这个问题吗?我完全为这个问题感到震惊。

javascript html getelementsbyclassname
1个回答
0
投票

如果结构始终相同,则可以使用Node.parentElement到达那里,从对Node.parentElement的引用开始:

<button>
document.addEventListener('click', ({ target }) => {
  if (target.tagName !== 'BUTTON') return;
  
  console.log(target.parentElement.outerHTML);  
});

或者,如果不同按钮的结构可能不同,则需要类似jQuery的<div class="div"><button type ="submit">a</button></div> <div class="div"><button type ="submit">b</button></div> <div class="div"><button type ="submit">c</button></div>。您可以使用循环和.closest()

实现类似的操作
© www.soinside.com 2019 - 2024. All rights reserved.