我正在获取并显示笔记(卡片)列表。每个按钮都有一个删除按钮,该按钮调用删除功能。
删除功能获取列表和索引,然后从列表中弹出元素。
问题在于它总是弹出数组的最后一项。 另外请告诉我们是否有更好的方法
<script>
let gusername = null;
let gresponse;
let notes = {};
function handleNotesGet() {
notes = getNote();
}
async function deleteNote(nlist, index, nid) {
// var response = await fetch(
// "http://localhost:3000/api/user/" + gusername + "/note/" + nid,
// {
// method: "delete",
// headers: { "Content-Type": "application/json" }
// }
// );
// gresponse.innerHTML = await response.text();
console.log(index);
nlist.pop(index);
notes = nlist;
}
async function getNote() {
console.log("Username", gusername);
var response = await fetch("http://localhost:3000/api/user/" + gusername, {
method: "get",
headers: { "Content-Type": "application/json" }
});
if (response.status == 200) {
return JSON.parse(await response.text());
} else {
throw Error(await response.text());
}
}
</script>
<div class="column">
<input
bind:value={gusername}
class="input"
type="text"
placeholder="Type username" />
<div class="control">
<button on:click={handleNotesGet} class="button is-info">
Get Notes
</button>
</div>
<br />
<div>
<code bind:this={gresponse} />
</div>
<div class="container">
<!-- Promise block begins here -->
{#await notes}
<p>...fetching</p>
{:then docs}
<!-- An array of objects is returned -->
{#each docs as doc, i}
<!--Display a card-->
<div class="box">
<article class="media">
<div class="media-content">
<div class="content">
<p>
<strong>{doc.title}</strong>
<small>@{doc.uid}</small>
<br />
<strong>{i}</strong>
<strong>{doc._id}</strong>
<!-- <small>{new Date(doc.dateCreated).toUTCString()}</small> -->
<br />
{doc.content}
</p>
</div>
<nav class="level is-mobile">
<div class="level-left">
<!-- bind the delete butto with func -->
<button
on:click={() => {
deleteNote(docs, i, doc._id);
}}
class="button is-small is-danger">
⌫
</button>
</div>
</nav>
</div>
</article>
</div>
{/each}
{:catch error}
<p style="color:red">{error.message}</p>
{/await}
<!-- -->
</div>
</div>
答案 0 :(得分:0)
方法arr.pop()
不接受参数
使用arr.splice(start, deleteCount)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice