首页 > 解决方案 > 如何通过事件目标获取上一个元素?

问题描述

我正在尝试div/ class/ wrapper/ container通过event.targetReact javascript 获取上一个。它是一张桌子,这是DOM树。当我单击带有“1”的单元格时,event.target 将输出

<div class="id">
  <span>1</span>
</div>

我怎样才能让它输出<div class="Table row">呢?谢谢

桌子:

id name location
1  test test      #the below html dom is for this row

DOM:

<div class="Table row" custom_att="test">
  <div class="id">
    <span>1</span>
  </div>
  <div class="name">
    <span>test</span>
  </div>
  <div class="location">
    <span>test</span>
  </div>
</div>

代码:

onMouseDownEvent(e){
    var ele = e.target;
    //do something with ele
}

标签: javascripthtmlxmldomelement

解决方案


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>event.target demo</title>
  <style>
  span, strong, p {
    padding: 8px;
    display: block;
    border: 1px solid #999;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<div class="Table row">
  <div class="id">
    <span>1</span>
  </div>
  <div class="name">
    <span>test</span>
  </div>
  <div class="location">
    <span>test</span>
  </div>
</div>
 <div id="log">
   
 </div>
<script>
$( "body" ).click(function( event ) {
 
  $( "#log" ).html( "clicked: " + event.target.parentNode.nodeName );
});
</script>
 
</body>
</html>


推荐阅读