【问题标题】:How to add "selected" to Select control option on option selection如何在选项选择时将“选定”添加到选择控制选项
【发布时间】:2020-08-11 20:22:42
【问题描述】:

我有一个函数可以从页面中提取标题并将它们作为选项添加到 HTML select 组件中。但是,我无法将所选项目作为选择器中显示的所选选项。如何以编程方式将“选定”属性添加到选定的选项?

<SelectControl
   label="Select heading for jump link"
   value={jumpLink}
   id="selectheader"
   options={[jumpLink]}
   onChange={setJumpLink}
/>


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

【问题讨论】:

  • 你如何确定应该选择哪一个?标准是什么?
  • @Code-Apprentice - 这是 Gutenberg Block SelectControl 组件 (developer.wordpress.org/block-editor/components/select-control) 问题的一部分,我试图弄清楚,我如何在我选择的选项。
  • “关于我选择的选项”你是如何选择它的?
  • WordPress Gutenberg 中的SelectControl 组件呈现普通的&lt;select&gt; 控件,并且是在Gutenberg 中使用select 控件的正确方法。我确实注意到我可以通过select.addEventListener('change', e =&gt; {console.log(e.target.options.selectedIndex);}); 在控制台中获取所选选项的值,但不知道如何将selected 属性设置为所选选项。
  • 在您的 for 循环中。 opt 是前一个 map() 正确的字符串。在map() 中,尝试打印item.selected 以查看是否可以在遍历项目时直接获取它。

标签: javascript html-select wordpress-gutenberg setattribute


【解决方案1】:

这是一个问题,您如何设置选定选项的选定状态,以便将其设置为组件中的视图。诀窍是将setTimeout 向上移动。

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

【讨论】:

    猜你喜欢
    • 2012-11-29
    • 2017-08-23
    • 2020-10-07
    • 1970-01-01
    • 2018-05-18
    • 2015-09-29
    • 2022-11-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多