【问题标题】:Returning variable´s value from first function and using it in second function从第一个函数返回变量的值并在第二个函数中使用它
【发布时间】:2018-02-01 11:22:08
【问题描述】:

所以我想单击列表中的一个项目并获取该项目的索引。单击一个项目将显示内容元素。单击该内容元素应该会给我首先单击的项目的(索引+1)。到目前为止,我收到“NaN”错误。我到底做错了什么?传递正常的字符串值似乎可行。

<div class="item-list">
  <div class="item">Item1</div>
  <div class="item">Item2</div>
</div>
<div class="hidden" style="display: none">Content</div>

$(function() {
    var thisIndex;
    $('.item-list .item').click(function(event) {
       var thisIndex = $('.item-list .item').index(this)
       $('.hidden').css('display', 'block')
    });
    $('.hidden').click(function(event) {  
       var nextIndex = thisIndex + 1;
       console.log(nextIndex)
    });
})

js 小提琴https://jsfiddle.net/zv0Lza6n/4/

【问题讨论】:

  • 是什么让您认为在一个函数中声明的变量可以在另一个函数中访问?如果要使用外部变量,请从函数中删除 var

标签: jquery variables click


【解决方案1】:

您在 click 函数之外声明 thisIndex 变量,然后在 click 函数中再次声明。声明一次,然后在函数中为其赋值。

$(function() {
    var thisIndex; 

    $('.item-list .item').click(function(event) {
        thisIndex = $('.item-list .item').index(this);
      $('.hidden').css('display', 'block');
    });
    $('.hidden').click(function(event) {  
      var nextIndex = thisIndex + 1;
      console.log(nextIndex);
    });
});

你还少了几个分号。

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2020-11-20
    • 2018-02-19
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多