Насколько я понимаю, у вас есть ячейка таблицы со структурой меню внутри нее. Вы хотите идентифицировать ячейку таблицы, в которой находится меню, по щелчку по меню, чего можно достичь, подняв DOM от цели события, пока не дойдете до ячейки (или не исчерпаете предков).
Проще, если вы подключите слушателей динамически, тогда этот внутри слушателя будет элементом, по которому щелкнули. В противном случае вы должны передать это или событие, например,
<p onclick="displayTableData(this)">Closed</p>
или
<p onclick="displayTableData(event)">Closed</p>
Следующее должно помочь вам:
// Attach listeners
window.onload = function() {
var nodes = document.querySelectorAll('.dropdown-content p').forEach(
node => node.addEventListener('click', displayTableData, false)
);
}
/* Return first ancestor of node that has tagName
** @param {HTMLElement} node - node to start from
** @param {string} tagName - tag name of element to find
** @returns {HTMLElement|undefined} - first matching ancestor or null if none found
*/
function getAncestor(node, tagName) {
if (!node || !tagName) return;
while (node.parentNode) {
node = node.parentNode;
if (node.tagName && node.tagName.toLowerCase() == tagName) {
return node;
}
}
return null;
}
function displayTableData(evt) {
// Stop bubbling
evt.stopPropagation();
var cell = getAncestor(this, 'td');
console.log(`cellIndex: ${cell && cell.cellIndex}`);
}
function myFunction5(node) {
console.log(`myFunction5: ${node.tagName} ${node.cellIndex}`);
}
<table>
<tr>
<td id="td01" onclick="myFunction5(this)">
<div class="dropdown">
<button class="dropbtn">Change?</button>
<div class="dropdown-content">
<p>OPEN </p>
<p>Closed</p>
</div>
</div>
</td>
</tr>
</table>
Существует также element.closest , который должен иметь разумную поддержку с указанным выше в качестве запасного варианта.
// Attach listeners
window.onload = function() {
var nodes = document.querySelectorAll('.dropdown-content p').forEach(
node => node.addEventListener('click', displayTableData, false)
);
}
function displayTableData(evt) {
// Stop bubbling
evt.stopPropagation();
var cell = this.closest('td');
console.log(`cellIndex: ${cell && cell.cellIndex}`);
}
function myFunction5(node) {
console.log(`myFunction5: ${node.tagName} ${node.cellIndex}`);
}
<table>
<tr>
<td id="td01" onclick="myFunction5(this)">
<div class="dropdown">
<button class="dropbtn">Change?</button>
<div class="dropdown-content">
<p>OPEN </p>
<p>Closed</p>
</div>
</div>
</td>
</tr>
</table>