gpt4 book ai didi

Javascript - classList 事件监听器的问题

转载 作者:行者123 更新时间:2023-12-02 23:06:59 24 4
gpt4 key购买 nike

我有一个“+”按钮,单击该按钮时,会触发创建一个带有输入和 2 个按钮的 block ,一个用于验证输入,一个用于删除输入。

enter image description here

//我的代码看起来几乎像这样:

    addBtn.addEventListener('click', e => {
addClick++;

// All the elements of the same line (input and 2 buttons) have an int in common in their id string ==> addClick

// I'm missing all the declarations of the variables here
blockDiv.appendChild(posteInput);
blockDiv.appendChild(validateBtn);
blockDiv.appendChild(deleteBtn);
globalPostesBlock.appendChild(blockDiv)

let allDeleteBtn = document.getElementsByClassName('delete-button');

for (let i = 0; i < allDeleteBtn.length; i++) {

allDeleteBtn[i].addEventListener('click', e => {

// Retrieving the block with the same id
let deleteBtnId = parseInt((allDeleteBtn[i].getAttribute('id').match(/\d+/g)).toString());
let singlePosteBlock = document.getElementById(`poste-block-${deleteBtnId}`);
singlePosteBlock.remove();
}

})
}

事件监听器代表单击删除按钮的操作,以便它可以删除其整个包含 block

我对验证按钮有相同的逻辑,但我在其中使用了 ajax。

每次创建一个新 block 时,我都想创建一个与该 block 关联的事件监听器,但到目前为止我发现的只是每个按钮上都有一个循环的事件监听器,所以发生的情况是该操作由于循环,触发次数与 block 数一样多,但我不知道如何分离每个事件监听器。

如果我有 3 个 block ,并且我验证了随后插入到数据库中的一个输入值,则该值将被插入 3 次。

最佳答案

这有帮助吗?

//id pool
let latestId = 0;

//retrive the button
var myButton = document.querySelector("button");

myButton.addEventListener("click", createKids);

//function declaration :: createKids
function createKids() {
latestId++;
//declare and initialization
let div = document.createElement("div");
let input = document.createElement("input");
let buttonSend = document.createElement("button");
let buttonDelete = document.createElement("button");

//append input & buttons to div
div.appendChild(input);
div.appendChild(buttonSend);
div.appendChild(buttonDelete);

//Some beautifying
buttonSend.innerText = "Send me";
buttonDelete.innerText = "Delete me";

//some logic
div.dataset.id = latestId;

//event handeling
buttonSend.addEventListener("click", sendItem);
buttonDelete.addEventListener("click", deleteItem);

//insert div
document.body.appendChild(div);
}

function sendItem(event) {
//do action and delete ?
let input = event.target.parentNode.querySelector("input");


//retrive data
let val = input.value;
let id = event.target.parentNode.dataset.id;

//disable input for fun ^^
input.disabled = true;

//console istead of send
console.log(id,val);

//handle some more
setTimeout(() => {
event.target.parentNode.remove();
}, 3000);
}

function deleteItem(event) {
event.currentTarget.parentNode.remove();
}
<p>Does this help?</p>
<button>Magic Button</button>

关于Javascript - classList 事件监听器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544532/

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