繁体   English   中英

为什么不能将函数内部的值赋给外部声明的变量(globaly)?

[英]Why cannot assign value inside a function to variable declared outside (globaly)?

我不知道为什么我不能将.hover函数捕获的值赋给全局声明的变量。

这是我的jQuery代码:

jQuery(function($){

  var receipt;

  $("#cartItems tr.cItem").hover(

        function()
        {
            $(this).addClass("highlight");
            receipt = $(this).next().children().text();
            console.log(receipt);
        },
        function()
        {
            $(this).removeClass("highlight");
        }
    );

    console.log(receipt);

  });

这是我的HTML:

<table id="cartItems">
  <tr>
     <td>Lp.</td><td>z:</td><td>na:</td><td>cena netto:</td>
  </tr>
  <tr class="cItem">
      <td>ru</td><td>pl</td><td>16.00</td>
  </tr>
  <tr>
      <td colspan="4">some simple text that should be assigned </td>
  </tr>
 </table>

第一个console.log(receipt) (内部.hover函数)工作正常并输出some simple text..而第二个输出没有。

请帮忙。

谢谢大家快速回复。 你们都对.hover功能完全正确。 我的错。 但现在我有另一个相关的问题。 我需要这个值将它传递给像这样调用的“qTip”插件:

$("#cartItems tr.cItem").qtip(
{
    content: receipt,
    show: 'mouseover',
    hide: 'mouseout'
 });

我应该以某种方式合并这个电话吗?

对console.log的“第二次”调用实际上是第一次(它在文档准备就绪时发生),此时你的var没有被定义

只有在调用悬停功能后,该值才会分配给receipt 您在#cartItems tr.cItem被悬停之前登录到控制台。

正如其他人所提到的那样,您当前放置了console.log(receipt)receipt尚未初始化。

如果您想将其更改为更有意义的内容,您可以:

  1. 将变量声明移到on load函数之外
  2. 在自己的函数中调用console.log(receipt),您可以在加载函数之后附加到click事件或任何其他操作。
 var receipt; jQuery(function ($) { $("#cartItems tr.cItem").hover( function () { $(this).addClass("highlight"); receipt = $(this).next().children().text(); console.log(receipt); }, function () { $(this).removeClass("highlight"); }); }); function printConsole() { console.log(receipt); } 

这是一个显示这个的jsfiddle演示。

请注意,当它第一次输出值时,它是undefined因为当页面首次加载时,悬停事件尚未触发,因此变量未初始化。 在您悬停并单击链接后,它现在有一个值。

第二个console.log就其在代码中的布局方式而言,发生在悬停之前,因此变量未定义。 在您悬停后,它会正确记录下一个tr的子项的文本。 这是一个jsfiddle,你的代码工作正常。 http://jsfiddle.net/63xKR/

hover()函数仅在您实际悬停在元素上时执行。 所以你写的基本上是:

var receipt = null;
var documentReady = someFunctionToBeExecutedLater(){ doesnt matter whats in here };
console.log(receipt);

如你所见,没有人实际调用函数(documentReady()),因此收据将保持为null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM