【问题标题】:Dynamically set name attribute of input field in loop with AlpineJS使用 AlpineJS 在循环中动态设置输入字段的名称属性
【发布时间】:2020-12-13 21:25:45
【问题描述】:

我想在 AlpineJS 的循环中设置隐藏输入字段的 name 属性。我试过x-bind:name 但这不起作用。

我认为这不起作用,因为在如何添加待办事项时使用了x-model

<input x-model="todoText" type="text">

<button x-on:click.prevent="addTodo('new', todoText)">
    Add
</button>

我怎样才能使下面的工作,以便将todos 数组中的索引键设置为todoSingle.id 值?

<template x-for="todoSingle in todoArray" :key="todoSingle.id">
    <input type="hidden" name="todos[todoSingle.id][id]" x-model="todoSingle.id">
    <input type="hidden" name="todos[todoSingle.id][type]" x-model="todoSingle.type">
    <input type="hidden" name="todos[todoSingle.id][description]" x-model="todoSingle.description">
</template>

更新

代码笔here。如果您添加一个待办事项,然后返回输入字段并输入,您会看到在每个按键上都添加了相同的待办事项。

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    您需要将x-bind:name 与模板字符串一起使用:

    <input type="hidden" x-bind:name="`todos[${todoSingle.id}][id]`" x-model="todoSingle.id">
    <input type="hidden" x-bind:name="`todos[${todoSingle.id}][type]`" x-model="todoSingle.type">
    <input type="hidden" x-bind:name="`todos[${todoSingle.id}][description]`" x-model="todoSingle.description">
    

    查看固定Codepen

    【讨论】:

    • 如原始问题中所示x-bind:name 不起作用。发生的情况是,在输入字段中的每个键上都会添加待办事项。我在我的问题中添加了输入字段和添加待办事项的按钮。
    • 我也收到了Can't find variable todoSingleCan't find variable todos
    • 你有这个在codepen中运行吗?或完整的组件代码
    • 我会创建一个,只需几分钟
    • 答案已更新并将 codepen 分叉到工作状态codepen.io/hugodf/pen/xxVqOeb
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多