jQuery 将 $(this) 传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7767593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:15:21  来源:igfitidea点击:

jQuery Passing $(this) to a Function

jquerythisparameter-passing

提问by Vahid

I have lines of code like this:

我有这样的代码行:

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

It works well. But I need to run these lines multiple times. So I have created a function and pass $(this) parameter to a function:

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

myFunc( $(this) );

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

But in this way, It didn't work.

但这种方式,它没有奏效。

回答by erimerturk

you can check this link.

你可以检查这个链接。

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

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>

回答by Muhammad Tahir

jQuery will automatically invoke your function with the proper context set.

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

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

function myFunction() {
    var that = $(this);
    console.log(that);
}

回答by Krzysztof Przygoda

If you work in no-conflict mode(i.e. out of global scope), one of the possibilities is:

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

jQuery.noConflict();

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

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

function myFunction() {
    var that = jQuery(this);
    console.log(that);
}

回答by Shaun O'Toole

You can pass the id to the function. With your loop inside the function.

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

myFunc(this.id);

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

I would normally do the loop outside the function like below:

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

$(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);
}