我正在尝试使用 alpine JS 构建一个自定义添加和从数组中删除整个 div 元素,这是我的代码,它正在工作,但不是从确切的删除按钮中删除,而是单击它将删除数组中的最后一个元素。
超文本标记语言
<div x-data="addRemove()">
<template x-for="(field, index) in fields" :key="index">
<div>
<input type="text" name="txt1[]" class="form-input">
<button type="button" class="btn btn-danger btn-small" @click="removeField(index)">×</button>
</div>
</template>
<button type="button" @click="addNewField()">+ Add Row</button>
</div>
Run Code Online (Sandbox Code Playgroud)
脚本语言
return {
fields: [],
addNewField() {
this.fields.push({});
},
removeField(index) {
this.fields.splice(index, 1);
}
}
Run Code Online (Sandbox Code Playgroud) alpine.js ×1