JavaScript添加EventListener

时间:2017-07-19 06:55:26

标签: javascript

我已经通过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 个答案:

答案 0 :(得分:5)

使用this

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>

答案 1 :(得分:2)

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

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

})
}
&#13;
<body>
<button id='delete'>Delete</button>
<button id='save'>Save</button>
</body>
&#13;
&#13;
&#13;