[英]how to remove a div from the html using ajax
我正在嘗試從網頁中刪除一個 div(及其子項,如果它包含的話)。
這是我正在使用的 ajax 代碼。
$.ajax({
url: window.location,
method: 'POST',
dataType: 'text',
data: {
delete_id: 1,
to_delete:deleteID
}, success: function (response) {
//Remove this node
$('.display_stts').removeChild(response); //It does not work
}
});
ajax 代碼返回這個,我想從頁面中刪除它。
<div class="card gedf-card">
<div class="card-body ml-10" style="padding:5px;">
<p class="card-text" style="color:blue; font-size:15px; text-align: justify;" name="cmtSpace" id="cmtSpace">
some text some text some text
</p>
<div class="text-right mr-5 replies">
<a class="card-link reply" href="javascript:void(0)" data-stID="124" onclick="stt_func(this)">
<i class="fa fa-reply"></i>continue
</a>
</div>
</div>
</div>
<br>
而這個ajax response
html 代碼位於名稱為 class class="display_stts"
的 div 中:
<div class="display_stts" id="display_stts">
<!-- displaying here -->
</div>
在這個 class class="display_stts"
中,我有多個元素,例如 ajax 返回的元素。但我只想刪除那個特定的元素。
我怎么能做到呢?
感謝您抽出時間回答我的問題。
你可以嘗試用你的 ajax 隱藏 div。首先在你的 div 中放置一個顯示樣式,比如內聯,就像這樣
<div class="display_stts" id="display_stts" style="display:inline">
<!-- displaying here -->
然后在您的 ajax 中,您可以通過將其設置為不顯示來像這樣在成功后隱藏
$.ajax({
url: window.location,
method: 'POST',
dataType: 'text',
data: {
delete_id: 1,
to_delete:deleteID
}, success: function (response) {
//Remove this node
var x = document.getElementById("display_stts");
x.style.display = "none";
}
});
由於您已經擁有deleteID
,因此似乎根本不需要使用 HTML 響應:您可以檢索具有data-stID
屬性的元素(使用$('[data-stID="' + deleteID + '"]')
),然后使用.closest()
向上遍歷 DOM 樹,直到到達所需的元素:我們在此處定位.gedf-card
。
放在一起,代碼應該是這樣的:
$.ajax({
url: window.location,
method: 'POST',
dataType: 'text',
data: {
delete_id: 1,
to_delete:deleteID
}, success: function () {
var cardToRemove = $('[data-stID="' + deleteID + '"]').closest('.gedf-card');
cardToRemove.remove();
}
});
試試這個解決方案,它會幫助你。
function RemoveJSElement() {
var html = "<div id='myElement'><div class='display_stts' id='display_stts'><div class='card gedf-card'></div><br></div></div>";
var containerdiv = document.createElement('div');
containerdiv.innerHTML = html;
alert(containerdiv.innerHTML);
var display_stts = containerdiv.getElementsByClassName('display_stts')[0];
display_stts.parentElement.remove(display_stts);
alert(containerdiv.innerHTML);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.