下拉元素选择和 JS 调用不起作用

Dropdown element selection and JS call is not working

本文关键字:JS 调用 不起作用 选择 元素      更新时间:2023-09-26

我有一个HTML页面,里面有一个下拉菜单和一个按钮。

选择一个元素后,按下按钮,我调用函数按照以下代码进行操作:

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Custom dropdown</title>
        <link rel="stylesheet" href="cssdropdown/style.css">
  </head>
  <body>
    <h3>Restart any service from here</h3>
<!--form method="post" action="example_new.php"-->
<span class="custom-dropdown">
    <select name="restart-component" id="restart-component">
        <option value=0>Data 1</option>
        <option value=1>Data 2</option>
    </select>
</span>
<button id="submit" name="submit" style="background-color:#1abc9c padding-left: 2cm;" onclick='goToRestart();'>Restart</button>
<p>Legend</p>
<br/>
<script type="text/javascript">
    function goToRestart() {
        alert ("into js");
        var url;
        var location = document.getElementById("restart-component").selectedIndex;
        if (location == 1) {
            url = 'http://www.page.com/west';
        }
        else if (location == 2) {
            url = 'http://www.page.com/land';
        }
        #window.location.href=url;
        alert(url)
    }
</script>
    <script src='http://ajax.googleapis.com/ajax/libs/prototype/1.7.1/prototype.js'></script>
        <script src="jsdropdown/index.js"></script>
  </body>
</html>

但是我的JavaScript函数从未被调用过。我错过了什么吗?请帮忙。

函数包装在onLoad()中或更改脚本,如下所示

<script type="text/javascript">
(function() {
   // your page initialization code here
   // the DOM will be available here
  function goToRestart() {
    alert("into js");
    var url;
    var location = document.getElementById("restart-component").selectedIndex;
    if (location == 1) {
      url = 'http://www.page.com/west';
    } else if (location == 2) {
      url = 'http://www.page.com/land';
    }
    window.location.href = url;
    alert(url);
  }
})();
</script>

先尝试注释此行

/

/#window.location.href=url;

<script type="text/javascript">
    function goToRestart() {
        alert ("into js");
        var url='empty';
        var location = document.getElementById("restart-component").selectedIndex;
        if (location == 1) {
            url = 'http://www.page.com/west';
        }
        else if (location == 2) {
            url = 'http://www.page.com/land';
        }
        //#window.location.href=url; //this line
        alert(url)
    }
</script>

当然,您会喜欢使用"尝试捕获"

脚本上存在语法错误。尝试:

 function goToRestart() {
    alert("into js");
    var url;
    var location = document.getElementById("restart-component").selectedIndex;
    if (location == 0) {
        url = 'http://www.page.com/west';
    } else if (location == 1) {
        url = 'http://www.page.com/land';
    }
    //#window.location.href=url; line with syntax error on the character #
    window.location.href = url;
    alert(url);

然后将函数的调用从 onclick='goToRestart();' 更改为仅onclick='goToRestart()'

希望对你有帮助