简体   繁体   English

如何在不传递事件参数的情况下获取触发“onclick”事件的元素?

[英]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.

相关问题 如何获取触发“ onclick”事件的元素 - How to get the element that fired the “onclick” event 如何从外部触发的自定义插件内部获取事件而不将其作为参数传递? - How to get event from inside a custom plugin fired from the outside without passing it as an argument? JS元素onclick事件未触发 - JS element onclick event not being fired 触发JavaScript onclick事件,无需任何点击 - JavaScript onclick event fired without any click 如果我具有onclick函数,如何获取引发事件的div? - How to get div that fired event if i have function onclick on it? 点击时未触发onclick事件 - onclick event not fired on clicking jQuery:如何在事件处理程序 function 中获取事件 object 而不将其作为参数传递? - jQuery: How to get the event object in an event handler function without passing it as an argument? 常规脚本:选择触发了按键事件的输入元素,而不实际传递ID等 - General script: selecting the input element for which keypress event is fired, without actually passing the ID etc 将另一个元素的ID传递到按钮的onclick事件中? - Passing the id of another element into the onclick event of a button? 如何在第一次按下回车键时停止第一个 onclick 事件的元素 - How to stop element with first onclick event to be fired when enter key is pressed first time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM