简体   繁体   English

是否有可能为 javascript 函数提供调用它的元素的 innerHTML 作为参数?

[英]Is there a possibility to give a javascript function the innerHTML of the element it is called from as a parameter?

I have a function that takes a String as a parameter to do certain things.我有一个函数,它接受一个字符串作为参数来做某些事情。 I want to bind that function to a button so it is called onclick and takes the innerHTML of the element as a parameter, is there any possibility to that without giving the button an id or without queryselector?我想将该函数绑定到一个按钮,因此它被称为 onclick 并将元素的 innerHTML 作为参数,如果不给按钮一个 id 或没有查询选择器,是否有任何可能性?

<button onclick="myFunction(myString)">Name XY</button>

There are about 500 Elements like this so i wanna avoid giving each one a unique element大约有 500 个这样的元素,所以我想避免给每个元素一个独特的元素

Use event delegation so you add one click handler.使用事件委托,以便您添加一键式处理程序。

 document.querySelector("#wrapper").addEventListener("click", function (e) { var button = e.target.closest("button.action"); if (button) { console.log(button.textContent); e.preventDefault(); } });
 <div id="wrapper"> <button class="action">1</button> <button class="action">2</button> <button class="action">3</button> <button class="action">4</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM