如何正确地在Svelte中动态添加和删除文本输入字段?
我是Svelte和Web开发的新手,希望您可以将我指向正确的方向。
默认情况下应该显示一个文本字段,同时允许在动态添加的按钮上添加并删除附加的文本字段。 当前,此代码可以动态添加文本字段,但是,它无法在按钮点击上动态删除文本字段。
我相信getDynamicElement函数可能会出现错误。但是,我不确定到底在哪里。有什么建议吗?
PS我知道这里有一些答案很接近,但我认为它们不适用于这种情况,尤其是在Svelte上。
<script>
var num_links = 1;
let container;
const GetDynamicElement = (value) => {
return (
'<input name = "DynamicField" type="text" size =111 id =link placeholder="Enter Next link! " value = "' +
value +
'" />' +
'<input type="button" value="Remove" on:click = {RemoveField(this)}>'
// "RemoveSuggestionCart(this)" />'
);
};
const addField = () => {
if (num_links < 2) {
console.log("addField");
const div = document.createElement("DIV");
div.innerHTML = GetDynamicElement("");
container.appendChild(div); // Append timetable space
num_links += 1;
}
};
//Removes the entire division inclusive of it's text field.
const RemoveField = (div) => {
console.log("RemoveField");
div.removeChild(div.parentNode);
num_links -= 1;
};
</script>
<div>
<input
name="DynamicField"
type="text"
size="121"
id="link"
placeholder="Enter First Link!"
/>
<div bind:this={container} />
</div>
<button on:click|preventDefault={addField}>[+ add timetable link]</button>
<style>
</style>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加/删除字段,并有一个按钮进行日志或发送到端点或使用“日志”按钮的任何内容。
尝试:
编辑:谢谢@Corrl-编辑。
Add/ remove fields and have a button to log or send to endpoint or whatever with "Log" button.
Try: https://svelte.dev/repl/2441993f8d9946aa894bf07a8a8f9b4f
Edited: thanks @Corrl - edited nicer.
您可以使用
num_link
和Svelte's>
使用Svelte创建输入:
工作示例:
You can use your
num_link
and svelte's#each
to create to inputs using svelte:Working example: https://svelte.dev/repl/04169e030b6944258cfd07af15873b48?version=3.48.0