【问题标题】:Finding index of element that was selected查找所选元素的索引
【发布时间】:2015-05-07 12:20:35
【问题描述】:

我正在关注 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);

控制台输出的是“未定义”,而不是获得点击标签的索引。我该怎么做才能解决这个问题?

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

【问题讨论】:

  • 这是因为您在单击任何内容之前就记录了变量。

标签: javascript jquery html css


【解决方案1】:

你需要将console.log()移到点击事件中,像这样:

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


};

现在,console.log() 会在文档就绪后立即运行,因为它会在 main 执行时运行。因为还没有发生点击事件,所以索引变量没有值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多