2017-06-21 94 views
-1

我+按鈕複製元素和 - 按鈕刪除最後附加元素。刪除點擊附加項目與jQuery

$('#btnNewMobilePhone').on('click', function(e){ 
      e.preventDefault(); 
      $('.phonemobile').append(' <div class="form-group"><label for="email" class="col-sm-3 control-label">Cep Telefonu</label><div class="col-sm-4"><input type="text" class="form-control" name="phone_mobile[]" placeholder="Mobile Phone"></div><div class="col-sm-2"> <a href="#" class="btn btn-primary btnRemMobilePhone"> <i class="entypo-plus"> -</i> </a> </div></div>'); 
}); 
$('.phonemobile').on('click', '.btnRemMobilePhone', function(e){ 
      e.preventDefault(); 
      $('.phonemobile .form-group:last').remove(); 
}); 

此代碼刪除最後添加的元素。但我想刪除最後一個元素的單擊元素。可能嗎?我找不到解決方案。

有使用類似

.form-group:this 
+0

哪裏有[mcve]?這看起來完全不清楚。 –

回答

1

您可以使用上下文(this)點擊的元素的遍歷最接近父form-group元素,然後將其刪除:

$('.phonemobile').on('click', '.btnRemMobilePhone', function(e){ 
    e.preventDefault(); 
    $(this).closest('.form-group').remove(); 
}); 
0

要刪除最後一個點擊的元素的方式,你應該使用:

$('.phonemobile .form-group').find(e.currentTarget).remove();

e.currentTarget將你點擊內部的該元素form-group並刪除它們。如果你想刪除只有那些被點擊和外在形式族元素,你應該使用$(e.currentTarget).remove();