【问题标题】:Add and Remove dom elements using alpine JS使用 alpine JS 添加和删除 dom 元素
【发布时间】:2021-12-19 22:20:48
【问题描述】:

我正在尝试使用 alpine JS 从数组中构建自定义添加和删除整个 div 元素,这是我的代码,它正在运行,但不是从确切的删除按钮中删除,而是单击它会删除数组中的最后一个元素。

HTML

<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)">&times;</button>
    </div>
  </template>
  <button type="button" @click="addNewField()">+ Add Row</button>
</div>

JAVASCRIPT

return {
        fields: [],
        addNewField() {
            this.fields.push({});
        },
        removeField(index) {
            this.fields.splice(index, 1);
        }
    }

【问题讨论】:

    标签: alpine.js


    【解决方案1】:

    找到了解决办法,我就是这么做的。

    HTML

    <div x-data="addRemove()">
      <template x-for="(field, index) in fields" :key="field.id">
        <div>
          <input type="text" name="txt1[]" class="form-input">
          <button type="button" class="btn btn-danger btn-small" @click="removeField(field)">&times;</button>
        </div>
      </template>
      <button type="button" @click="addNewField()">+ Add Row</button>
    </div>
    

    JAVASCRIPT

    function addRemove() {
        return {
            fields: [],
            addNewField() {
                this.fields.push({id: new Date().getTime() + this.fields.length});
            },
            removeField(field) {
                this.fields.splice(this.fields.indexOf(field), 1);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2019-02-21
      • 1970-01-01
      • 2017-07-19
      • 2019-10-20
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多