jQuery 将 $(this) 传递给函数

jQuery Passing $(this) to a Function

提问人:Vahid 提问时间:10/14/2011 最后编辑:Lightness Races in OrbitVahid 更新时间:5/29/2019 访问量:99868

问:

我有这样的代码行:

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

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

myFunc( $(this) );

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

但这样一来,它就没有奏效了。

jquery 这个 参数传递

评论

1赞 Rob 10/14/2011
如果您使用“this”而不是“$(this)”作为参数会怎样?
2赞 Tim Rogers 10/14/2011
你的代码没有写出来,所以我建议这是其他地方的错误。你说的“它不起作用”是什么意思?
0赞 Vahid 10/15/2011
我使用了“这个”,但它也不起作用。当我在 Firebug 中看到 $this 和 thisObj 时,它显示: {$this = input.focus} 但是 {thisObj = [input.focus]} ...有什么区别吗?
0赞 simple guy 12/14/2017
你@Natasha解决这个问题的?

答:

83赞 erimerturk 10/14/2011 #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>

17赞 Muhammad Tahir 5/30/2015 #2

jQuery将自动调用具有正确上下文集的函数。

$('#button').on('click', myFunction);

function myFunction() {
    var that = $(this);
    console.log(that);
}
2赞 Krzysztof Przygoda 3/21/2018 #3

如果您在无冲突模式下工作(即超出全局范围),则其中一种可能性是:

jQuery.noConflict();

(function ($) {
    $('#button').on('click', myFunction);
}(jQuery));

// or
jQuery('#button').on('click', myFunction);

function myFunction() {
    var that = jQuery(this);
    console.log(that);
}
-1赞 Shaun O'Toole 5/29/2019 #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);
}