[英]How to get the element that fired the “onclick” event without passing event argument?
How can i get the DOM element which fired onclick, in this situation : 在这种情况下,如何获取触发onclick的DOM元素:
<div onclick="ajax('?section=panel');">Hi</div>
and the ajax function is : 和ajax函数是:
function ajax(url)
{
alert(caller_element.innerHTML); // I need `caller_element` contain a reference to that DIV
...xmlhttp(url)...
}
Note that i cannot change HTML, i can only change ajax()
function. 请注意,我无法更改HTML,我只能更改
ajax()
函数。
Try this HTML code: 试试这个HTML代码:
<div onclick="ajax(this, '?section=panel');">Hi</div>
and JS: 和JS:
function ajax(caller_element, url)
{
alert(caller_element.innerHTML);
...xmlhttp(url)...
}
You can use Function.prototype.call
to set the context of a function, like so: 您可以使用
Function.prototype.call
来设置Function.prototype.call
的上下文,如下所示:
<div onclick="ajax.call(this, '?section=panel');">Hi</div>
function ajax(url) {
alert(this.innerHTML);
...xmlhttp(url)...
}
It would be just as easy to pass it as an argument, though. 尽管如此,传递它作为一个论点也同样容易。
This is impossible without modifying the HTML. 如果不修改HTML,这是不可能的。 If your situation permits, you could use the
id
tag... 如果您的情况允许,您可以使用
id
标签...
<div id="whatever" onclick="ajax('?section-panel');">Hi</div>
function ajax(url) {
alert(document.body.getElementById("whatever").innerHTML);
...xmlhttp(url)...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.