如何从javascript中的子元素获取主父节点元素的属性值?

How to get attribute value of the main parent node element from a child element in javascript?

是否可以在点击子元素时获取属性'data-id'?在下面的场景中,getDataIdOfTheCurrentRow() 方法仅在单击跨度而不是整个记录时出现。我需要检索父 tr 的 attr 值。我知道我可以设置一个在单击 'tr' 时触发的方法,这样我就可以轻松访问它的属性。但这不是我要的。

 <tr data-id="1">
     <div>
          <div>
              <div id="text-wrapper">
                  <span onclick="getDataIdOfTheCurrentRow(event)">some text</span>
              </div>
          </div>
     </div>
 </tr>


function getDataIdOfTheCurrentRow(event) {
   // stopPropagation is used to only fires the method when clicking on the child element, not other methods on the parent elements
    event.stopPropagation(); 
}

你可以使用 closest(selector):

function getDataIdOfTheCurrentRow(event) {
    event.stopPropagation();
    const row = event.target.closest('tr');
    if(row.hasAttribute('data-id')){
      const dataID = row.getAttribute('data-id');
      // now do your thing
    }
}
  • <tr> 的唯一有效父标签是 <table>

    将所有内容包装在 <table>

  • <tr> 可以拥有的唯一子标签是 <td><th>

    直接在 <tr> 中添加 <td> 删除那些多余的 <div> 它们只会使您的布局混乱

  • 不要如此随意地使用 id,当您写完第 100 页时您就会明白,很难重写样式,添加 JavaScript 引用 DOM 对象等

    删除所有 id 并使用 document.querySelector() 通过 .class[name]tagName 等引用元素

  • 不要使用内联事件处理程序

     <div class='target' onclick="lame(this)">DON'T DO THIS</div>
    

    使用一个事件属性或

    document.querySelector('.target').onclick = eventHandler;
    

    事件侦听器

    document.querySelector('.target').addEventListener('click', eventHandler)
    

有关事件的文章链接见下方

详情在示例中注释

// Bind click event to an ancestor tag
document.querySelector('table').onclick = getRow;

// Event handlers only passes the Event object
function getRow(event) {
  // Reference the tag that the user clicked
  const clicked = event.target;
  // If the clicked tag is a <button>...
  if (clicked.matches('button')) {
    /*
    Find the closest parent <tr> get it's data-id value and convert it 
    into a real number
    */
    console.log(parseInt(clicked.closest('tr').dataset.id));
  }
}
.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

.as-console-wrapper {
  min-height: 100% !important;
  max-width: 50%;
  margin-left: 50%;
}
<table>
  <tr data-id="1">
    <td>
      <menu>
        <button type='button'>Get row number</button>
      </menu>
    </td>
  </tr>
  <tr data-id='2'>
    <td>
      <menu>
        <button type='button'>Get row number</button>
      </menu>
    </td>
  </tr>
  <tr data-id='3'>
    <td>
      <menu>
        <button type='button'>Get row number</button>
      </menu>
    </td>
  </tr>
  <tr data-id='4'>
    <td>
      <menu>
        <button type='button'>Get row number</button>
      </menu>
    </td>
  </tr>
</table>

Events

Event Delegation

Inline event handlers are garbage