Javascript-单击div中的按钮时检索div的值

问题描述

我正在编写代码以编辑数据库表。

我有以下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);
}

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

  • “父级” div的ID;
  • 同一“父” div中三个可编辑的div中每个div的内容

是否可以使用纯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);
}

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