简体   繁体   中英

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 :

<div onclick="ajax('?section=panel');">Hi</div>

and the ajax function is :

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.

Try this HTML code:

<div onclick="ajax(this, '?section=panel');">Hi</div>

and 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:

<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. If your situation permits, you could use the id tag...

<div id="whatever" onclick="ajax('?section-panel');">Hi</div>

function ajax(url) {
    alert(document.body.getElementById("whatever").innerHTML);
    ...xmlhttp(url)...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM