passing $(this) from function to function

后端 未结 3 534
旧时难觅i
旧时难觅i 2021-01-23 12:01

I have 2 different event on different classes :

$(\'.box1\').click(function(){
$(this).find(\'something\').css(\'red\')
}

$(\'#otherId .box2\').change(function(         


        
相关标签:
3条回答
  • 2021-01-23 12:26

    The keyword this can't be used as an argument, but you can keep using this within the function body:

    function getDetails()
    {
        $(this).find(".something").css('red');
    }
    

    And then call it like so:

    $('#otherId .box2').change(function() {
        getDetails.call(this);
    }
    

    See also: Function.call()

    0 讨论(0)
  • 2021-01-23 12:36

    You can use something like this to pass it through if you want to get an inputs value then change it and output the final value next to it:

    var finalOutput;
    
    function getDetails(args) {
        args = "Hello World";
        return args;
    }
    
    $('.box2').change(function(){
        var inputValue = $(this).val();
        finalOutput = getDetails(inputValue);
    
        $('.box2').after('<b>' + finalOutput + '</b>');
    });
    

    Here is a working example:

    http://jsfiddle.net/La4v9mL0/

    0 讨论(0)
  • 2021-01-23 12:39

    this is a keyword so it can't be a param name

    function getDetails(el) {
        el.find(".something").css('red');
    }
    
    $('#otherId .box2').change(function () {
        getDetails($(this))
    })
    
    0 讨论(0)
提交回复
热议问题