jQuery Passing $(this) to a Function

后端 未结 4 1625
轻奢々
轻奢々 2021-01-30 20:11

I have lines of code like this:

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

It works well. But I need to run

4条回答
  •  误落风尘
    2021-01-30 20:41

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

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

提交回复
热议问题