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

czo*_*ela 3 html javascript variables jquery scope

我不知道为什么我不能将.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);

  });
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

第一个console.log(receipt)(内部.hover功能)工作正常,输出some simple text..,第二个输出没有.

请帮忙.

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

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

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

soj*_*oju 5

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