简体   繁体   English

单击按钮后如何检查事件是否发生

[英]How to check if event occurred after clicking on a button

I have the following HTML table format (just showing one row out of many) which has a button on the last cell:我有以下 HTML 表格格式(仅显示一行中的一行),在最后一个单元格上有一个按钮:

 <div id=main> <div class='info'> <p>Name: <span class='x'>ABC</span></p> <p>Number: <span class='x'>0</span></p> <table class='newTable'> <tr> <th> Number </th> <th> Value </th> <th> Go </th> </tr> <tr> <td> 0 </td> <td> <span class='k'>11.7</span> </td> <td> <button class='go'>Go</button> </td> </tr> </table> </div> </div>

I have an eventListener ( mainEntries.addEventListener('click', clickFunction) ) which triggers whenever inside <div id = main> ... </div>我有一个 eventListener ( mainEntries.addEventListener('click', clickFunction) ),它在<div id = main> ... </div>内触发

I am not allowed to change the HTML.我不允许更改 HTML。 I have two questions:我有两个问题:

  1. How do I check inside function clickFunction(e) if I clicked on the button "GO" or somewhere inside <div id = main> ... </div>如果我单击按钮“GO”或<div id = main> ... </div>内部的某个位置,如何检查function clickFunction(e)内部

***inside clickFunction(e) e is the MouseEvent ***在clickFunction(e) e 里面是MouseEvent

  1. If I click on the button how can I get the text inside first cell of the same row?如果我点击按钮,我怎样才能在同一行的第一个单元格中获取文本?

As already was mentioned, you can use e.target to get clicked element.如前所述,您可以使用e.target来获取点击元素。 Then, you can use combination of closest() and cells.item() functions of the found button:然后,您可以使用找到的按钮的closest()cells.item()函数的组合:

 const mainEntries = document.querySelector('#main'); const clickFunction = e => { if (e.target.tagName === 'BUTTON' && e.target.classList.contains('go')) { const firstCellSameRow = e.target.closest('tr').cells.item(0).innerText; console.log('GO button clicked. First cell\'s text at the same row is ', firstCellSameRow); } else { console.log('Main div clicked outside of GO button'); } } mainEntries.addEventListener('click', clickFunction);
 <div id=main> <div class='info'> <p>Name: <span class='x'>ABC</span></p> <p>Number: <span class='x'>0</span></p> <table class='newTable'> <tr> <th> Number </th> <th> Value </th> <th> Go </th> </tr> <tr> <td> 0 </td> <td> <span class='k'>11.7</span> </td> <td> <button class='go'>Go</button> </td> </tr> <tr> <td> 2 </td> <td> <span class='k'>8.5</span> </td> <td> <button class='go'>Go</button> </td> </tr> </table> </div> </div>

I added another distinct row for showing different logs.我添加了另一个不同的行来显示不同的日志。

1) you should consider e.target inside function clickFunction(e) 1)你应该在function clickFunction(e)中考虑e.target

2) you should select the grandparent of that button, then, from the parent, you select the first child. 2)您应该选择该按钮的祖父母,然后从父母中选择第一个孩子。 buttonElement.parentNode.parentNode.children[0].innerText

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM