Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mouseover事件始终使用for()循环中的最后一个索引 A. B C 变量类=['a','b','c']; 对于(var i=0;i_Javascript_Jquery - Fatal编程技术网

Javascript Mouseover事件始终使用for()循环中的最后一个索引 A. B C 变量类=['a','b','c']; 对于(var i=0;i

Javascript Mouseover事件始终使用for()循环中的最后一个索引 A. B C 变量类=['a','b','c']; 对于(var i=0;i,javascript,jquery,Javascript,Jquery,这是我所能创造的问题的最简单再现。鼠标移动元素时,有两件事出错: log(i)总是记录“3”,这没有意义,因为循环结束于2 classes[i]返回Undefined,即使我只是在脚本顶部定义了它 改用.each()和.filter()扩展名。这将解决很多问题,因为您不必使用整数。要执行此操作,请参阅以下代码: <html lang="en"> <head> <script src="https://code.jquery.com/jquery-1.10.2.j

这是我所能创造的问题的最简单再现。鼠标移动元素时,有两件事出错:

  • log(i)
    总是记录“3”,这没有意义,因为循环结束于2
  • classes[i]
    返回Undefined,即使我只是在脚本顶部定义了它
  • 改用
    .each()
    .filter()
    扩展名。这将解决很多问题,因为您不必使用整数。要执行此操作,请参阅以下代码:

    <html lang="en">
    <head>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
    
    <div class="a" style='font-size:50'>a</div>
    <div class="b" style='font-size:50'>b</div>
    <div class="c" style='font-size:50'>c</div>
    
    <script>
    var classes = ['a', 'b', 'c'];
    for (var i = 0; i < classes.length; i++) {
      $("."+classes[i]).mouseover(function() {
        console.log(i);
        console.log(classes[i]);
      });
    }
    </script>
    
    </body>
    </html>
    

    当该函数被执行时,它会查找
    i
    ,它会在哪里找到它,它的值是什么?在循环结束之前,变量i变为3。因为这是javascript(有时会有点奇怪),除非您重新分配i,否则它将保留该值,即使循环结束后该值超出范围。因此,当事件实际触发时,i=3,因此它打印3。但是数组只指向2,因此类[3]没有定义。如果你想知道发生火灾的班级,使用$(this.prop('class')。那么
    $('.a、.b、.c')如何。每个(…)
    ?或者直接去:
    $('.a、.b、.c')。鼠标悬停(…)
    ?取决于OP在mouseover处理程序中真正想要做什么。但这一切都不是问题的核心:)@JamesThorpe我不知道你能这么做。。。稍微简单一点:)。谢谢你的提示,非常有用的语法简化,谢谢!不知道那是针对谁的,但我很高兴:)
    $('div').filter(function() {
      return $(this).hasClass('a') || $(this).hasClass('b') || $(this).hasClass('c'); //gets any divs with the class 'a', 'b', or 'c'
    }).each(function(){ // performs a function on each of these divs
      console.log($(this).text()); // logs each divs inner text (change as required)
    })