Jquery each():回调中的变量总是有最后一个值? [英] Jquery each(): variable in callback always has last value?

查看:32
本文介绍了Jquery each():回调中的变量总是有最后一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法弄清楚这里发生了什么.

http://jsfiddle.net/Sth3Z/

它应该对每个链接都这样做,而不是无论悬停在哪个链接上,它都只会更改最后一个链接.

解决方案

$link 之前添加 var: http://jsfiddle.net/Sth3Z/1/

 $('.navItem').each(function() {var $link = $(this).children('a');//`var` 添加

目前,您正在声明一个全局变量,它将在循环中的每次迭代中被覆盖.

Can't seem to figure out what's going on here.

<div id="navigation">
    <ul id="navList">
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX.html">Discover</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/documentation.html">Documentation</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/download.html">Download</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/donate.html">Donate</a></li>
    </ul>
    <script type="text/javascript">
        $('.navItem').each(function() {
            $link = $(this).children('a');
            $link.hover(
                function() {
                    $link.css('width', '224px');
                },
                function() {
                    $link.css('width', '192px');
                }
            )
        });            
    </script>
</div>

http://jsfiddle.net/Sth3Z/

It should be doing it for each link, instead it only changes the last link no matter which one is being hovered over.

解决方案

Add var before $link: http://jsfiddle.net/Sth3Z/1/

    $('.navItem').each(function() {
        var $link = $(this).children('a');   // `var` added

Currently, you're declaring a global variable, which will be overwritten at each iteration in the loop.

这篇关于Jquery each():回调中的变量总是有最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆