我有两个监听器:一个调用另一个。问题是第二个(嵌套的)侦听器是否知道文档中触发第一个侦听器的位置?我的意思是,当我为一列中的50个字段使用addEventListener,并且在此侦听器中调用另一个侦听器时,第二个侦听器“知道”第一个侦听器的位置(我是指单击的字段)?我试图解决这个问题-不知道第二个侦听器是否以某种方式“继承”了第一个侦听器的‘变量’值。例如:
document.querySelectorAll("#decisionList").forEach(elem => elem.addEventListener("change", function () {
var selectedOptionIndex = this.options[this.selectedIndex].index;
var invoiceDateText = this.closest('tr').querySelector('.payment').textContent.trim();
var finalChoice = this.closest('tr').querySelector('.choice');
switch (selectedOptionIndex) {
case 0:
finalChoice.innerHTML = '<input type="date">'
break;
case 1:
finalChoice.innerHTML = '<input id="finalDate" type="date">'
finalDateListener(selectedOptionIndex, invoiceDateText); //here I'm passing variables keeping current values from main Listener
default:
finalChoice.innerHTML = ''
}}));
function finalDateListener(selectedOptionIndex, invoiceDateText){
const finalDate = document.getElementById("finalDate"); //'id' from parent Listener
finalDate.addEventListener("change", function () {
alert(invoiceDateText + ' ' + selectedOptionIndex);
});
}这段代码只适用于第二个侦听器的第一次触发(所以当我调用第一个侦听器,然后调用第二个侦听器时),对于下一个侦听器,它不会工作,不会显示警报。这是否意味着我需要再次在第二个侦听器中寻找最近的元素?
发布于 2020-10-21 07:25:34
如果使用document.createElement而不是在innerHTML中键入字符串来创建新的输入元素,则可以将新的输入元素传递给第二个函数,而根本不需要id。
document.querySelectorAll("#decisionList").forEach(elem => elem.addEventListener("change", (event) => {
console.log("you clicked " + event.target)
var finalChoice = event.target.closest('tr').querySelector('.choice')
var inputElement = document.createElement("input")
inputElement.type = "date"
finalChoice.appendChild(inputElement)
finalDateListener(inputElement, selectedOptionIndex, invoiceDateText)
}))
function finalDateListener(element, selectedOptionIndex, invoiceDateText){
console.log("the new input element is " + element)
element.addEventListener("change", ()=> {
console.log("changed")
})
}https://stackoverflow.com/questions/64454516
复制相似问题