gpt4 book ai didi

javascript - 添加和删​​除按钮 JavaScript

转载 作者:行者123 更新时间:2023-12-01 02:30:41 24 4
gpt4 key购买 nike

我需要添加和删除按钮来添加和删除输入。

我是否编写了普通脚本或添加按钮应该是另一个?

const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

最佳答案

我对 Anu 的答案做了一些修改,但这应该可以解决问题。

const add = document.getElementById("add");

var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";

var btn = document.createElement("BUTTON");
var t = document.createTextNode("X");
btn.id = i;
btn.appendChild(t);


btn.onclick = function() {
$('#' + i).remove();
$('#' + i).remove();
i = i - 1;
};
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

关于javascript - 添加和删​​除按钮 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com