查找所选元素的索引

Finding index of element that was selected

本文关键字:索引 元素 查找      更新时间:2023-09-26

我正在关注Semmy Purewal的书Learning Web App Development来学习html/css,javascript,jQuery等。在他的一个例子中,读者必须在网页上制作三个选项卡,并编写代码以使用户单击的选项卡具有一个名为"active"的类。

在我将该类添加到单击的选项卡中之前,我需要找出它的索引 - 这就是我遇到问题的地方。

这是我的HTML代码:

<!doctype html>
<html>
  <head>
    ...
  </head>
  <body>
    <header>
      ...
    </header>
    <main>
      <div class="container">
        <div class="tabs">
          <a href=""><span class="active">Newest</span></a>
          <a href=""><span>Oldest</span></a>
          <a href=""><span>Add</span></a>
        </div>
        <div class="content">
          <ul>
            ...
          </ul> 
        </div>
      </div>
    </main>
    <footer>
      ...
    </footer>
    <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

这是我的jQuery代码,用于获取用户选择的选项卡的索引(受Purewal强烈影响):

var makeActiveTab = function(tabNum) {
    //make all the tabs inactive
    $(".tabs span").removeClass("active");
    //make the first tab active
    $(".tabs a:nth-child(" + tabNum + ") span").addClass("active");
    //empty the main content so we can recreate it
    $("main .content").empty();
    //return false so we don't follow the link
    return false;
};
var main = function() {
    "use strict";
    var index;
    $(".tabs a").click("click", function() {
        index = $(this).index();
    });
    console.log(index);
};
$(document).ready(main);

控制台不是获取单击选项卡的索引,而是输出"未定义"。我该怎么做才能解决这个问题?

以下是我到目前为止咨询过的来源列表:

  • http://www.electrictoolbox.com/jquery-find-index-element-clicked/
  • 查找元素索引

你需要将 console.log() 移动到 click 事件中,如下所示:

var main = function() {
    "use strict";
    var index;
    $(".tabs a").click("click", function() {
        index = $(this).index();
        console.log(index);
    });

};

现在,console.log() 在文档准备就绪后立即运行,因为它在执行 main 时运行。由于尚未发生任何单击事件,因此索引变量没有值。