亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 AJAX 從數據庫和 DOM 中刪除對象

通過 AJAX 從數據庫和 DOM 中刪除對象

HUWWW 2023-07-20 10:47:24
所以我有一個簡單的 AJAX post 請求,它按照我的意愿從模型中刪除對象,但我很難正確地從 DOM 中刪除它。function removeFriend(id){    let dataId = `${id}`    $.ajax({        type: 'POST',        url: `/delete/friend`,        data: {            friend_id: `${id}`,            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),            action: 'post'        },        success: function(json){            let tbody = document.querySelector('tbody');            let row = tbody.querySelector('tr[data-id=dataId]');            console.log(row);            row.remove();            alert('friend has been deleted')        },        error: function(xhr, errmsg, err) {            console.log(error)        }    })}我不斷收到信息index.js:119 Uncaught TypeError: Cannot read property 'remove' of null,console.log(row) 顯示為空。我已經嘗試過let row = tbody.querySelector('tr[data-id=`${id}`]');并且結果相同。我已經嘗試過let row = tbody.querySelectorAll('tr[data-id=dataId]');,但 console.log(row) 的輸出是一個空的 NodeList,NodeList []后跟index.js:119 Uncaught TypeError: row.remove is not a function.這就是我的桌子的樣子:    <table class="table table-striped table-sm" id="my_friends">        <thead>            <tr>                <th>Nick name</th>                <th>First name</th>                <th>Last name</th>                <th>Likes</th>                <th>DOB</th>                <th>lives in</th>                <th>Remove friend</th>            </tr>        </thead>        <tbody>        {% for friend in friends %}        <tr data-id="{{ friend.id }}">            <td>{{friend.nick_name}}</td>            <td>{{friend.first_name}}</td>            <td>{{friend.last_name}}</td>            <td>{{friend.likes}}</td>            <td>{{friend.dob | date:"Y-m-d"}}</td>            <td>{{friend.lives_in}}</td>            <td><button type="button" class="remove-friend" name="remove-friend" value="{{ friend.id }}">Remove</button></td>        </tr>        {% endfor %}        </tbody>    </table>我知道我肯定已經正確分配了數據屬性,因為我可以看到它顯示在我的 Chrome 瀏覽器元素中。
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

使用傳遞給選擇器中刪除好友函數的 id

let row = tbody.querySelector(`tr[data-id="${id}"]`);


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號