0

我正在开发一个将按钮添加到网页的用户脚本。单击时我正在处理的按钮之一将创建一个弹出 div。我正在尝试在弹出窗口中创建一个动态选择/选项下拉列表,其中的选项来自一个数组。对于第二个下拉列表,我正在尝试根据上一个下拉列表中的选择创建一个动态下拉列表,但我不确定如何继续。我希望itemDropList根据typeDropList.

提前致谢!

到目前为止,这是我的代码:

var button = document.createElement('button'),
button.onclick = prompt;
function prompt() {
    var blockingDiv = document.createElement('div');
    blockingDiv.id = 'PopupBackground';
    var divPopup = document.createElement('div');
    divPopup.id = 'better1ClickSimTChangeCTIPopup';
    var content = document.createElement('div');
    content.id = 'Content';
    var typeDropList = document.createElement('select');
    typeDropList.id = 'TypeDropList';
    typeDropList.name = 'TypeDropList';
    typeDropList.onchange = changeItem(this.value);
    content.appendChild(typeDropList);
    var typeOptions =
        [
            {
                "text": 'Select Type',
                "value": '',
                "defaultSelected": true,
                "selected": true
            },
            {
                "text": 'Text 1',
                "value": 'A',
                "defaultSelected": false,
                "selected": false
            },
            {
                "text": 'Text 2',
                "value": 'B',
                "defaultSelected": false,
                "selected": false
            },
            {
                "text": 'Text 3',
                "value": 'C',
                "defaultSelected": false,
                "selected": false
            }
        ];
    for (var i = 0; i < typeOptions.length; i++) {
        var typeOption = document.createElement('option');
        typeOption.id = 'TypeOptions';
        typeOption.name = 'TypeOptions';
        var type = typeOptions[i];
        typeOption.appendChild(new Option(type.text, type.value, type.defaultSelected, type.selected));
        typeDropList.appendChild(typeOption);
    }
    var itemDropList = document.createElement('select');
    itemDropList.id = 'ItemDropList';
    content.appendChild(itemDropList);
    var typeItemOptions =
    {
        A: ['Item A 1',
            'Item A 2',
            'Item A 3'],
        B: ['Item B 1',
            'Item B 2',
            'Item B 3'],
        C: ['Item C 1',
            'Item C 2',
            'Item C 3']
    };
4

1 回答 1

0

如前所述,您的目标存在几个问题,但是由于您询问如何进行,我提供了这些建议。

  1. 将所有内容保存在单个 DOM 中,即具有单个上下文的单个网页。您可能已经这样做了,但如果不是,您的弹出窗口肯定会导致您在保持所有内容并发方面出现问题。

  2. 创建您的第一个下拉列表(选择和选项)并使其满意地将“结果”放入全局内存中。即使用 var 定义结果变量。

  3. 使用控制台确保您有正确的值来构建您的第二个下拉控件。

  4. 测试,测试,测试!使用内置的 Javascript 工具一步一步地进行,祝你好运!

从您的代码看来,您正在尝试在单个 Javascript 函数中完成所有操作。您需要将其分解为几个模块。它肯定需要至少两个功能。记住要使用好的设计技术,模块化代码就是这里的答案!

于 2021-09-14T18:15:27.657 回答