【问题标题】:jQuery Passing $(this) to a FunctionjQuery 将 $(this) 传递给函数
【发布时间】:2011-12-07 17:32:12
【问题描述】:

我有这样的代码行:

$(this).parent().parent().children().each(function(){
    // do something
});

效果很好。但我需要多次运行这些行。 所以我创建了一个函数并将 $(this) 参数传递给一个函数:

myFunc( $(this) );

function myFunc(thisObj) {
    thisObj.parent().parent().children().each(function(){
        // do something
    });
}

但是这样一来,就不行了。

【问题讨论】:

  • 如果你使用“this”而不是“$(this)”作为参数呢?
  • 您编写的代码没有任何问题,所以我建议这是其他地方的错误。 “它没有用”是什么意思?
  • 我用过“this”,但它也不起作用。当我在 Firebug 中看到 $this 和 thisObj 时,它会显示: {$this = input.focus} 但是 {thisObj = [input.focus]} ... 有什么区别吗?
  • @Natasha 你解决了这个问题吗?

标签: jquery this parameter-passing


【解决方案1】:

您可以查看此链接。

http://jsfiddle.net/zEXrq/38/

$("#f").click(function() {
  myFunc($(this));
})

function myFunc(thisObj) {
  thisObj.parent().parent().children().each(function() {
    alert("childs")
  });
}
<div id="wordlist">
  <div id="a"></div>
  <div id="b">
    <div id="e"></div>
    <div id="f">child</div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    jQuery 将使用适当的上下文集自动调用您的函数。

    $('#button').on('click', myFunction);
    
    function myFunction() {
        var that = $(this);
        console.log(that);
    }
    

    【讨论】:

      【解决方案3】:

      如果您在no-conflict mode 工作(即在全球范围之外),其中一种可能性是:

      jQuery.noConflict();
      
      (function ($) {
          $('#button').on('click', myFunction);
      }(jQuery));
      
      // or
      jQuery('#button').on('click', myFunction);
      
      function myFunction() {
          var that = jQuery(this);
          console.log(that);
      }
      

      【讨论】:

        【解决方案4】:

        您可以将 id 传递给函数。在函数内部使用循环。

        myFunc(this.id);
        
        function myFunc(thisid) {
            $("#" + thisid).parent().parent().children().each(function(){
                // do something
            });
        }
        

        我通常会在函数外执行如下循环:

        $(this).parent().parent().children().each(function(){
            myFunc(this.id)
        });
        
        function myFunc(thisid) {
        
            // do something example
           $("#" + thisid).html("Yay, i changed the html for element: " + thisid);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-12-11
          • 2020-10-10
          • 1970-01-01
          • 2010-11-01
          • 1970-01-01
          • 2012-02-19
          • 1970-01-01
          • 2013-06-25
          • 1970-01-01
          相关资源
          最近更新 更多