简体   繁体   English

防止在每次点击时添加 DOM 元素

[英]Prevent DOM elements from being added on every click

I have the following script which gets DOM elements with a given class, and adds them to an array.我有以下脚本,它使用给定的 class 获取 DOM 元素,并将它们添加到数组中。 It then loops over the array and adds the values to option elements for a SelectControl component in WordPress Gutenberg.然后它循环遍历数组并将值添加到 WordPress Gutenberg 中SelectControl组件的option元素。 I'm able to get the elements into the array into the dropdown, but I'm receiving the following error: Uncaught TypeError: Cannot read property 'appendChild' of null in the console.我能够将数组中的元素放入下拉列表中,但我收到以下错误:未捕获的类型错误: Uncaught TypeError: Cannot read property 'appendChild' of null It also doesn't show the selected option in the select component when selected and duplicates the array options in the dropdown every time an option from the dropdown is selected.选择时,它也不会在 select 组件中显示所选选项,并且每次选择下拉列表中的选项时都会复制下拉列表中的数组选项。

I suspect it may be an execution sequence issue, but not completely sure:我怀疑这可能是执行顺序问题,但不完全确定:

setTimeout(() => {
            let headers = [...document.querySelectorAll('.wp-block-heading')].map(item => item.innerText);
            const select = document.getElementById('selectheader');
            for (let i = 0; i < headers.length; i++) {
                let opt = headers[i];
                let el = document.createElement('option');
                el.textContent = opt;
                el.value = opt;
                select.appendChild(el);
            }
        }, 1000);


<SelectControl
    value={[headers]}
    id="selectheader"
    options={[headers]}
    onChange={setJumpLink}
/>

It actually needed:它实际上需要:

if (select && select.innerHTML) {
    select.innerHTML = '';
}

before the loop.在循环之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM