簡體   English   中英

使用jQuery單擊按鈕時在div中刪除一行

[英]Delete a row in div when click the button using jQuery

在此處輸入圖片說明

如上圖所示,單擊x按鈕時,我試圖刪除該行。

我創建了一個div <div id="records"> </div> ,它不斷使用jQuery將內容附加到$("#records").prepend(new_record)中。

我實現該行的方式是:

var new_record = username + " " + $("#client-name").val() + $("#reams").val()+ " "+ "<button id='btn-sm'> x </button>"

在這里,我只是將包括按鈕的每個部分附加到變量new_record

但是,單擊按鈕后,我將停留在如何刪除此特定行上,因為每個按鈕都與其他按鈕相同。 有沒有更好的方法來實現這一目標?

您將需要一種識別整個行的方法,以便將每個條目包裝在div或其他元素中。 然后,由於元素是動態添加的,因此您需要使用委托事件處理-感測父元素中的單擊,然后檢查真正的來源是否來自特定類型的子元素-jQuery很簡單。 此代碼段查找被單擊按鈕的父div並將其刪除。

$('#records').on('click', 'button', function() {
  $(this).parent('div').remove(); 
});

 var username = "test"; var new_record = "<div>" + username + " " + $("#client-name").val() + $("#reams").val() + " " + "<button id='btn-sm'> x </button></div>"; $("#records").prepend(new_record); $("#records").prepend(new_record); $("#records").prepend(new_record); $('#records').on('click', 'button', function() { $(this).parent('div').remove(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="records"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM