Javascript的getElementsByClassName()无法找到合适的类

时间:2018-01-15 02:38:21

标签: javascript

我一直在尝试使用以下指南对标签进行简单的表单设置:https://www.w3schools.com/howto/howto_js_form_steps.asp.

我有三个div = class =" tab"在表单中,我试图使用javascript使其可见/不可见:

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
      // This function will display the specified tab of the form...
      var x = document.getElementsByClassName("tab");
      x[n].style.display = "block";
}

这应该显示第n个选项卡,但是在加载页面时没有可见的标签,而且,当页面加载并且n = 0时,两个按钮(上一个和下一个,见下面的代码)都是可见的;我试图使用以下方法使用不同的设置:

<script> // code goes here </script>

或者只是包含一个单独的.js文件,将脚本部分嵌入到head,body,html甚至表单中都是不成功的。一直以来,我都可以在同一个脚本部分的开头运行简单的js命令,例如:alert(&#34; test&#34;);.

我在带有预制Bitnami LAMP堆栈的Linux机器上运行该页面。

<!Doctype html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles/login.css" />
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/new_user.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <script>

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {

    // This function will display the specified tab of the form...
    var x = document.getElementsByClassName("tab");
    x[n].style.display = "block";

    //... and fix the Previous/Next buttons:
    if (n == 0) {
        document.getElementById("prevBtn").style.display = "none";
    } else {
        document.getElementById("prevBtn").style.display = "inline";
    }
    if (n == (x.length - 1)) {
        document.getElementById("nextBtn").innerHTML = "Submit";
    } else {
        document.getElementById("nextBtn").innerHTML = "Next";
    }
    //... and run a function that will display the correct step indicator:
    fixStepIndicator(n)
}

function nextPrev(n) {

    // This function should figure out which tab to display
    var x = document.getElementsByClassName("tab");

    // Hide the current tab:
    x[currentTab].style.display = "none";
    // Increase or decrease the current tab by 1:
    currentTab = currentTab + n;
    // if you have reached the end of the form... :
    if (currentTab >= x.length) {
    //...the form gets submitted:
        document.getElementById("register_form").submit();
        return false;
    }
    // Otherwise, display the correct tab:
    showTab(currentTab);
}

// This manages step indicators.
function fixStepIndicator(n) {
    // This function removes the "active" class of all steps...
    var i, x = document.getElementsByClassName("step");
    for (i = 0; i < x.length; i++) {
        x[i].className = x[i].className.replace(" active", "");
    }
    //... and adds the "active" class to the current step:
    x[n].className += " active";
}

</script>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body class="background">
    <main class="wrapper">
        <div id="parent">
            <form id="register_form" action="" method="post">
                <h1>New user:</h1>
                <div style="text-align:center;">
                    <span class="step"></span>
                    <span class="step"></span>
                    <span class="step"></span>
                </div>
                <div style="float:right; padding: 15px;">
                    <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
                </div>
                <div style="float:left; padding: 15px;">
                    <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
                </div>
                <div class="tab">
                        //content
                </div>

                <div class="tab">
                        //content
                </div>

                <div class="tab">
                       //content
                    </div>
                </div>
            </form>
        </div>
    </main>

</body>

</html>

选项卡类本身看起来像默认情况下应该是不可见的:

.tab {
  display: none;
}

我想找出为什么表单中的标签似乎不受showTab函数的影响。我已经在这个问题上待了几个小时,我绝对无能为力,任何帮助都将不胜感激!

亲切的问候。

2 个答案:

答案 0 :(得分:2)

您的代码的第一个问题是,在加载页面之前javascript正在运行。因此它不会起作用。在调用函数之前,必须等待页面加载。有几种方法,通常有一个库。

在纯JavaScript中,您可以在文档上侦听 DOMContentLoaded 事件,如下所示:

<script>
  var currentTab = 0; // Current tab is set to be the first tab (0)

  function showTab(n) {
      // This function will display the specified tab of the form...
      var x = document.getElementsByClassName("tab");
      x[n].style.display = "block";
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    // this code will be running when the document is loaded
    showTab(currentTab); // Display the current tab

  });
</script>

答案 1 :(得分:0)

我不确定这是否100%准确,但下面的代码显示了对代码的一些改进。

我更喜欢querySelectorAll,因为我可以传入任何CSS选择器。

我使用forEach来浏览标签和步骤。

我只获得一次标签,因为这不会改变。

但我并不是100%确定CSS做了什么,所以我不能保证这段代码正是你所需要的。

  

要完成这项工作,您必须在所有HTML之后放置<script>。将其作为<body>中的最后一个孩子。请勿在{{1​​}}

之前第一次致电showTabs

body.onload
var currentTab = 0; // Current tab is set to be the first tab (0)
var tabs = document.querySelectorAll(".tab");
showTab(currentTab); // Display the current tab

function showTab(n) {
  tabs.forEach(
    function(tab, i) {
      // This function will display the specified tab of the form...
      tab.style.display = n===i ? 'block' : 'none';
    }
  );

  //... and fix the Previous/Next buttons:
  if (n == 0) {
      document.getElementById("prevBtn").style.display = "none";
  } else {
      document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (tabs.length - 1)) {
      document.getElementById("nextBtn").innerHTML = "Submit";
  } else {
      document.getElementById("nextBtn").innerHTML = "Next";
  }
  //... and run a function that will display the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // Hide the current tab:
  tabs[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= tabs.length) {
    //...the form gets submitted:
    document.getElementById("register_form").submit();
    return false;
  }

  // Otherwise, display the correct tab:
  showTab(currentTab);
}

// This manages step indicators.
function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var steps = document.querySelectorAll(".step");
  if (steps) {
    steps.forEach(
      function(step, i) {
        step.classList.toggle("active", n === i);
      }
    );
  }
}