使用函数制作的 HTML 元素具有相同的事件侦听器

HTML elements made with function have same event listener

本文关键字:侦听器 事件 HTML 函数 数制 元素      更新时间:2023-09-26
const add_compressor = (number) => {
    let div = document.createElement('div');
        div.className = 'compressor';
    let threshold = document.createElement('input');
        threshold.type = 'number';
        threshold.className = 'input_number';
        threshold.addEventListener('input', () => {
            compressors[number].threshold.value = threshold.value;
        })
    div.appendChild(threshold);
    added_effects.appendChild(div);
}
add_button.addEventListener('click', () => {
    if (select_effect.value != 'Add Effect...') {
        if (select_effect.value === 'compressor') {
            compressors[compressors.length] = effects[select_effect.value];
            add_compressor(compressors.length - 1);
        }
    }
})

我正在尝试允许使用此add_compressor函数为 Web 音频 API 创建多个压缩器。除了threshold.addEventListener链接到创建的每台压缩机之外,一切都可以正常工作。我想知道是否可以以这种方式为多个压缩器创建事件侦听器。这是一个JS小提琴,在控制台中显示了问题。

https://jsfiddle.net/0L1my6kp/

更改压缩机

的任何输入框都将更改所有压缩机的阈值。

问题是你只创建一个压缩器对象一次,并且每次都引用同一个对象。

所以取而代之的是这个

const effects = {
    compressor: context.createDynamicsCompressor()
}

它应该是

const effects = {
    compressor: context.createDynamicsCompressor
}

然后,当您单击该按钮时创建一个新的压缩器。查看更新的小提琴:https://jsfiddle.net/0L1my6kp/4/