I trying to get the target element's id when function fired, but `this` keyword returns `undefined`

后端 未结 1 776
予麋鹿
予麋鹿 2021-01-24 14:37

I trying to capture the target element\'s id when function fired, but this keyword returns undefined

--- HTML file. --- (I can\'t add any para

相关标签:
1条回答
  • 2021-01-24 15:17

    This is a very common question here on StackOverflow.

    In short, your onclick gets wrapped in an anonymous function (which does have access to this. You have to pass it along.

    --- HTML file. ---

    <a href="#some_links" id="element_id" onclick = "object.pageName.functionName(this, 'parms1', 'parms2', 'parms3')">Get this object</a>
    

    --- .js file ---

    object.pageName.functionName = function(self, a, b, c){
        alert(self); // returns 'undefined'
    }
    

    Here is another way:

    object.pageName.functionName = function(a, b, c){
        // Downside of this way, you can only use this function for one element.
        self = document.getElementById("element_id");
        alert(self);
    }
    
    0 讨论(0)
提交回复
热议问题