【问题标题】:How do I pass $(this) to a function?如何将 $(this) 传递给函数?
【发布时间】:2016-12-11 16:26:29
【问题描述】:

我的代码是:

$(document).ready(function(){

    var hCount = 0,
        eCount = 0,
        nCount = 0,
        mCount = 0;

$("#head").click(function() {
        var pPos = counter(hCount);
        $(this).animate({left:pPos+"px"}, 1000);
    });

function counter(count)
{
    count++;
    if(count === 10)
    {
        count = 0;
        pPos = 0;
    }
    else
    {
        var pPos = $(this).css('left');
        pPos = pPos.substring(0,(pPos.length-2))
        pPos -= 367;

    }

    return pPos;
}

我收到一条错误提示

未捕获的类型错误:无法读取未定义的属性“defaultView”

我不知道是什么导致了这个错误。

另外,我怎样才能将函数counter() 传递给$(this) 中的$("#head").click 的值?我不能直接提及$("#head"),因为我将使用除#head 之外的更多div 重复此功能,同时重用函数计数器中的代码。

【问题讨论】:

  • 请不要多问。问一个或另一个

标签: javascript jquery function parameter-passing this


【解决方案1】:

$(this) 和其他对象一样只是一个对象。只需将其传递到您的函数中:

counter(hCount, $(this));
....

function counter(count, thisFromPreviousFunction)

【讨论】:

    【解决方案2】:

    只需使用elem 参数扩展计数器函数并在点击处理中传递它:

    function counter(count, elem){
       // ...
    }
    
    $("#head").click(function() {
        var elem = $(this);
        var pPos = counter(hCount, elem);
        elem.animate({left:pPos+"px"}, 1000);
    });
    

    【讨论】:

    • 谢谢,但现在显然我有一个新问题。我需要在不使用全局变量的情况下从函数计数器传递pPoscount 的值。关于可以做什么的任何想法?
    • 从计数器返回列表:返回[pPos, counter],得到pPos作为result[0],count作为result[1],其中result=counter()
    • 最后一个问题,先生。有什么办法可以消除全局变量 hCount、eCount、nCount 和 mCount?
    • @SomenathSinha 另请注意,您的 hCount、eCount ... 不是全局变量。
    【解决方案3】:

    未捕获的类型错误:无法读取未定义的属性“defaultView”

    这来自于行 var pPos = $(this).css('left');

    因为$(this) 没有在您的函数中定义(该函数与 Selector 无关,因此 $(this) 并不像您想象的那样存在)。

    $(document).ready(function(){
    
        var hCount = 0,
            eCount = 0,
            nCount = 0,
            mCount = 0;
    
      $("#head").click(function() {
        var pPos = counter(hCount, $(this)); // Pass the selector
        $(this).animate({left:pPos+"px"}, 1000);
      });
    
      function counter(count, selector) {
          count++;
          if(count === 10)  {
              count = 0;
              pPos = 0;
          }
          else {
              var pPos = selector.css('left'); // Use the given selector
              pPos = pPos.substring(0,(pPos.length-2))
              pPos -= 367;
          }
          return pPos;
      }
    });
    

    https://jsfiddle.net/yw2b4tyt/

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 2011-04-07
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多