jQuery Passing $(this) to a Function

2019-03-08 23:48发布

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:

myFunc( $(this) );

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

But in this way, It didn't work.

3条回答
Anthone
2楼-- · 2019-03-09 00:08

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

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

function myFunction() {
    var that = $(this);
    console.log(that);
}
查看更多
趁早两清
3楼-- · 2019-03-09 00:17

you can check this link.

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>

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-09 00:28

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);
}
查看更多
登录 后发表回答