首页 > 解决方案 > 从下拉框中随机选择一个选项,然后单击以激活另一个在 Javascript 中使用 onChange 的函数

问题描述

onChange我将添加一个链接到此下拉框 ( )的脚本id="select-box-1",因为当我选择其中一个选项时,它将被激活。

该按钮id="botao-do-jogo-aleatorio-1"从选择框中随机选择一个选项。

但是目前当我单击随机选择按钮时,选择栏会出现选择的选项,但它不会激活onChange脚本,因为没有任何操作。

我怎样才能选择复选框但生成点击而不是像.selectedIndexIs doing 那样设置值?

<html>
    <head>
        <style>
        </style>
        <script id="random-number">
            function generateRandomIntegerInRange(min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }
        </script>
    </head>
    <body style="background-color:black;">
        <div class="row">
            <div class="column left">
                <form id="jogo-aleatorio-1" action="" method="post">
                    <button class="button" id="botao-do-jogo-aleatorio-1" style="width: 100%;" onclick="funcao_jogo_aleatorio_1()">Partida Aleatória 1</button>
                </form>
                <script id="script-da-caixa-de-selecao-suspensa-1">
                    function funcao_jogo_aleatorio_1() {
                        var btn = document.getElementById('jogo-aleatorio-1');
                        btn.onclick = function(e){ 
                            e.preventDefault();
                            document.getElementById("select-box-1").selectedIndex = generateRandomIntegerInRange(1, document.querySelectorAll("dl dt").length);
                        };
                    }
                </script>
                <form action="" method="post" id="formulario-radar-1">
                    <div id="caixa-suspensa-1">
                        <input type="text" id="barra-de-texto-para-radar-1" style="width: 283px;">
                    </div>
                </form>
                <select id="select-box-1" style="width: 100%;">
                    <option value="" market=""></option>
                    <option value="home" market="away">journey</option>
                    <option value="hotel" market="party">events</option>
                </select>
                <dl style="color:white;font-weight:bold;;overflow:hidden;overflow-y:scroll;">
                    <dt>journey</option>
                    <dt>events</option>
                </dl>
            </div>
        </div>
    </body>
</html>

标签: javascripthtmldrop-down-menuclickhtml-select

解决方案


这就是答案

let a = document.querySelectorAll(".dl dt");

for (let i = 0; i < a.length; i++) {
 a[i].addEventListener('click', function() {
  // code here and use 'this'
 };
};

使用for循环检查每个输入元素,否则您无法访问它。然后在这里 // 代码中插入函数、对象或数组,并使用“this”选择器来处理选定的输入。


推荐阅读