OnClick 具有特定 class 和 return 元素 ID 的众多元素之一被点击(更少的代码)

OnClick one of many elements with certain class and return id of element clicked (less code)

这只是一个例子,但假设我有这个:

<img class"clone" id="1" onClick="reply_click(this.id)">
<img class"clone" id="2" onClick="reply_click(this.id)">
<img class"clone" id="3" onClick="reply_click(this.id)">
..... x 100

<script type="text/javascript">
function reply_click(clicked_id)
{
    alert(clicked_id);
}
</script>

是否可以只对 class“克隆”进行一次 OnClick 并且 return 我单击的元素的 ID 以便我可以在函数中使用它?

我将使用不同的 ID 生成大约 100 张图像。

所以如果我必须在每一行中添加 onClick="reply_click(this.id) 自然会出现很多重复代码。

所以我希望的是:

onClick -> any element with class clone -> return me the exact ID of the element clicked

我在 JS 和 jQuery 中搜索了不同的东西,但我想我不知道我实际上在搜索什么。

感谢任何我应该查找的帮助或建议

使用 jQuery 你可以这样做:

function reply_click(clicked_id)
{
   alert(clicked_id);
}
    
$('img.clone').on('click', function(event) {   
    reply_click(event.target.id);
});

香草 JS (ES6):

const images = document.getElementsByClassName('clone');
images.forEach((img) =>
  img.addEventListener('click', (event) => reply_click(event.target.id))
);

您可以 select 所有具有 class clone 的元素,并以这种方式为每个元素添加一个事件侦听器:

const clones = document.querySelectorAll('.clone');

const divToCopyInto = document.querySelector(div);//get the div you want to copy into

clones.forEach((clone) => clone.addEventListener('click', (event) => {
    const newClone = clone.cloneNode(true); // or use event.target if you wish to clone the target which will probably be the image in this case
    divToCopyInto.appendChild(newClone);
}));

编辑:评论后,我在事件侦听器中添加了所需的功能。

你还应该看到 notes 关于 cloneNode 方法

除了上述答案之外,如果img元素在没有其他元素的情况下完全按照问题中的描述出现,您也可以将它们包装在容器中并在其上应用事件处理程序。

<div id = "img-wrapper">
    <img class"clone" id="1">
    <img class"clone" id="2">
    <img class"clone" id="3">
    <!-- etc -->
</div>

img-wrapper 上应用事件处理程序。

const imgWrapper = document.getElementById('img-wrapper');
imgWrapper.addEventListener('click', (event) => reply_click(event.target.id))