【问题标题】:How to select from list and click submit button then go to link "in HTML"如何从列表中选择并单击提交按钮,然后转到“in HTML”链接
【发布时间】:2022-02-11 00:37:56
【问题描述】:

我为我的项目找到了这段代码。我想将其更改为通过单击提交按钮打开网站

<html>
<body>
<form action="/action_page.php" method="get">
  <label for="cars">Choose a Site:</label>
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
  <input type="submit">
</form>
</body>
</html>

例如:当从列表中选择“Google”时,点击“提交”按钮打开“action_page.php”上存在的“www.google.com”

我没有“action_page.php”代码

【问题讨论】:

    标签: html list hyperlink submit


    【解决方案1】:

    首先,我修改了你的html代码:

    <html>
    <body>
    <form method="get">
      <label for="cars">Choose a Site:</label>
      <select id="site" name="site">
        <option value="Google">Google</option>
        <option value="Yahoo">Yahoo</option>
        <option value="MSN">MSN</option>
      </select>
    </form>
    <button type="button" id="button" >Submit</button>
    
    <script src="script1.js"></script>
    </body>
    </html>
    

    在表单外做了一个按钮,并引用了外部js文件script1.js

    然后我创建了 js 文件并将以下代码添加到其中:

    var select = document.getElementById('site');
    
    document.getElementById("button").onclick = function(){
        var value = select.value
        if (value == "Google")
        {
            window.location.href = "https://www.google.com/";
        }
        else if (value == "Yahoo")
        {
            window.location.href = "https://www.yahoo.com/";
        }
        else if (value == "MSN")
        {
            window.location.href = "https://www.msn.com/";
        }
    };
    

    它从 html 脚本中找到 select 标签和按钮,检查按钮是否被按下并根据下拉选择重定向到相应的网站。

    【讨论】:

    • 非常感谢。 :) 。你能更多解释一下吗?在新窗口中打开的网站怎么办? ,我想要超过 10 个列表,我该怎么做? "getElementById('site')" 和 "getElementById("button")" 再次感谢 :)
    • 嗨。使用 window.open(url) 在新窗口中打开。要添加更多列表,只需添加更多 option 标记和更多 if 语句,并在其条件中添加标记值。使用 getElementById("site")getElementById("button") 我搜索 id 为 sitebutton 的元素b> 在 html 代码中。
    • 再次感谢您的帮助:)
    • 怎样才能使用前面的“提交按钮”而不是底部
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多