如何通过在Javascript中单击链接,用链接的值设置下拉列表值

How to set dropdown list value with the value of a link by clicking that link in Javascript

本文关键字:链接 何通过 设置 下拉列表 Javascript 单击      更新时间:2023-09-26

我想通过点击链接为下拉列表设置一个值,我尝试过这样的方法,但它不起作用:

<html>
 <body>
    <select id="select">
       <option value="one">one</option>
       <option value="two">Two</option>
       <option value="three">Three</option>
    </select><br />
  <a class="link1" value="two" href="page.php?cc=two">Two</a><br /><br />
  <a class="link1" value="three" href="page.php?cc=three">Three</a>
  <script> 
       function setSelect () {
           var elmnt = document.getElementsByClassName('link1');
             for (i = 0; i < elmnt.length; i++) {
                    elmnt[i].onclick = function () {
                    document.getElementById('select').value = elmnt[i].getAttribute("value");
                    window.history.pushState('Form', 'My form', this.getAttribute("href"));
                    return false;
                    };                  
            }
       }

       setSelect ();
    </script>
 </body>
 </html>  

我还尝试通过点击链接将URL中的值输入下拉列表,但没有成功,所以我尝试用链接值设置下拉列表
任何帮助都将不胜感激。

在您的javascript代码中出现问题,请添加此

<script>
    function setSelect() {
        var elmnt = document.getElementsByClassName('link1');
        for (i = 0; i < elmnt.length; i++) {
            elmnt[i].onclick = (function (i) {
                return function () {
                    document.getElementById('select').value = elmnt[i].getAttribute("value");
                    window.history.pushState('Form', 'My form', this.getAttribute("href"));
                    return false;
                };
            })(i)
        }
    }
    setSelect();
</script>