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

时光总嘲笑我的痴心妄想 提交于 2020-01-21 19:44:10

问题


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

--- HTML file. --- (I can't add any parameter in onclick function) I have many <a> tag in the page and want to identify witch <a> tag was clicked.

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

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

--- .js file ---

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

回答1:


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


来源:https://stackoverflow.com/questions/12490110/i-trying-to-get-the-target-elements-id-when-function-fired-but-this-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!