2017-05-05 8 views
-2

謝罪 - 私は今CodePen上のものを作っています - https://codepen.io/cssgrid/pen/971328c046d97ffd24decafa20804d3b/イベントバブリングと、もともと再現可能なテストケースを持っていないため「この」おかしな

私は製品の束を持っています。誰かが各製品部門の内部にある削除ボタンをクリックするたびに、DOMから製品を削除したいと考えています。 私の問題は次のとおりです。実際に

$(".remove-btn").on("click", function() { 
$(this).closest(".product").remove(); 
}) 
+0

[MCVE]を提供してみ唯一つの項目があるので、あなたのコードは、最後の項目が削除されて示すものではありません。それを[ライブデモ](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)にしてみてください。 – Quentin

+0

私は問題を再現できません:http://jsbin.com/gaqabo/1/edit?html,output – Quentin

+0

'<>'をクリックして[mcve]を作成すると、コードが動作します - おそらくSOがコードをラップするオンロードで。あなたもそうです – mplungjan

答えて

0

:リストの最後の製品は、ユーザーが実際にクリックしたことにあるボタン:(また、jQueryのにしようとした

<div class="product"> 
//some code 
<button class="remove-btn">Remove</button> 
</div><!-- end of product div --> 

var products = document.querySelectorAll(".product"); 
for (let i = 0; i < products.length; i++) { 
    products[i].addEventListener("click", function(e) { 
     if (e.target.classList.contains("remove-btn")) { 
      this.remove(); 
     } 
    }) 
} 

を持つ製品ではなく、削除されていますあなたのコードは、さらに検査にうまく動作します。しかし、私は以下のことを、よりシンプルでクリーンなバージョンが含まれている。


をあなたはjqueryのを使用して気にしないと、

$('.remove-btn').click(function() { 
 
    $(this).parent('.product').remove(); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="product"> 
 
    <p>Lorem Ipsum 1</p> 
 
    <button class="remove-btn">Remove</button> 
 
</div> 
 
<div class="product"> 
 
    <p>Lorem Ipsum 2</p> 
 
    <button class="remove-btn">Remove</button> 
 
</div> 
 
<div class="product"> 
 
    <p>Lorem Ipsum 3</p> 
 
    <button class="remove-btn">Remove</button> 
 
</div> 
 
<div class="product"> 
 
    <p>Lorem Ipsum 4</p> 
 
    <button class="remove-btn">Remove</button> 
 
</div> 
 
<div class="product"> 
 
    <p>Lorem Ipsum 5</p> 
 
    <button class="remove-btn">Remove</button> 
 
</div>

+0

元のコードで何が間違っていましたか? – Quentin

+0

@Quentin - もし彼がjQueryを持っていれば、彼が委任できるときにイベントハンドラをループして追加するのは普通ではありません。 – mplungjan

+0

私は "元のコードはどうですか? (私がコードを実行したときに再現できなかった問題) – Quentin

関連する問題