Javascript - 当 div 中的按钮被点击时检索 div 的值

Javascript - Retrieving values of a div when a button inside that div is clicked

我正在编写代码来编辑数据库 table。

我有以下 HTML:

<div id="1">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>

<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>

<div id="2">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>

<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>

<div id="3">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>

<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>

以此类推

使用下面的函数,我可以得到被点击的按钮:

function a(value) {
  console.log(value);
}

单击按钮(保存或删除)时,我需要检索:

是否可以使用纯 Javascript?

任何建议将不胜感激。

提前致谢。

我会做的是在 JS 中实现点击监听器,这样我就可以很容易地查询元素。

示例如下:

// Query all div.div-editable elements
document.querySelectorAll('div.div-editable')
  .forEach((div) => {
    // The id of the parent
    const divId = div.id;

    // Each of content editable divs inside the parent div
    const editables = div.querySelectorAll('div[contenteditable]');

    // The buttons Save and Delete
    const saveBtn = div.querySelector('button.button-save');
    const deleteBtn = div.querySelector('button.button-delete');

    // Add click listeners to buttons
    saveBtn.addEventListener('click', function() {
      console.log('Saved: ' + divId);

      const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);

      console.log('Values of divs:', contentOfEditableDivs);
    });
    deleteBtn.addEventListener('click', function() {
      console.log('Deleted: ' + divId);

      const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);

      console.log('Values of divs:', contentOfEditableDivs);
    });
  });
<div id="1" class="div-editable">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>

<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>

<div id="2" class="div-editable">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>

<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>

<div id="3" class="div-editable">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>

<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>

编辑 1:添加了代码片段

编辑 2:简化说明

您可以在 click 的事件处理程序的参数中发送 this 关键字,然后访问父 div 的 id。

所以你的 HTML 看起来像:

// rest of the code here
<button onClick="a(this, 'save')">SAVE</button>
<button onClick="a(this, 'delete')">DELETE</button>
// rest of the code here

您的 JS 代码将更改为:

function a(elem, value) {
  console.log(elem.parentNode.id);
}

有关以下内容的更多详细信息link: how i get parent id by onclick Child in js