开发者问题收集

JavaScript 添加事件监听器

2017-07-19
80

我已经用 javascript 制作了 html。我们如何才能找出按下了哪个删除按钮

<div id="maindiv">        
    <div id="product_1">
        <input placeholder="Add Product Name" type="text">
        <input placeholder="Cost per unit" type="number">
        <input placeholder="Number of products" type="number">
        <button id="delete_1">Delete</button>
    </div>
    <div id="product_2">
        <input placeholder="Add Product Name" type="text">
        <input placeholder="Cost per unit" type="number">
        <input placeholder="Number of products" type="number">
        <button id="delete_2">Delete</button>
    </div>
</div>
2个回答

使用 这个

var btn = document.querySelectorAll('button')
btn.forEach(function(item) {
  item.addEventListener('click', function() {
    console.log('clicked id: ' + this.id);
  });
});
<div id="maindiv">
  <div id="product_1">
    <input placeholder="Add Product Name" type="text">
    <input placeholder="Cost per unit" type="number">
    <input placeholder="Number of products" type="number">
    <button id="delete_1">Delete</button>
  </div>
  <div id="product_2">
    <input placeholder="Add Product Name" type="text">
    <input placeholder="Cost per unit" type="number">
    <input placeholder="Number of products" type="number">
    <button id="delete_2">Delete</button>
  </div>
</div>
ewwink
2017-07-19

你可以试试这个。希望这能有所帮助。

var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++){
buttons[i].addEventListener('click',function(){
  console.log(this.id);

})
}
<body>
<button id='delete'>Delete</button>
<button id='save'>Save</button>
</body>
Aayushi
2017-07-19