javascript Javascript获取调用函数的dom元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10090943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript get the dom element a function was called from
提问by clamp
HTML part:
HTML部分:
<a href="#" onclick="callme();return false;">foo</a>
JS part:
JS部分:
function callme() {
var me = ?; //someway to get the dom element of the a-tag
$(me).toggle();
}
in the JS part can i somehow get the a-tag that this function was called from?
在 JS 部分,我可以以某种方式获取调用此函数的 a-tag 吗?
i know i could just pass it as a parameter, but this function is used many many times on a page and i want to avoid putting the parameter everywhere.
我知道我可以将它作为参数传递,但是这个函数在一个页面上多次使用,我想避免把参数放在任何地方。
thanks!
谢谢!
回答by Kevin B
Since you are using an onclick attribute (BAD!) you have to pass that into the function.
由于您使用的是 onclick 属性(糟糕!),您必须将其传递给函数。
onclick="callme(this); return false;"
and the js:
和js:
function callme(el) {
var $me = $(el);
$me.doSomething();
}
Another option is to set the context of the function using .call().
另一种选择是使用 .call() 设置函数的上下文。
onclick="callme.call(this,event)"
and the js
和 js
function callme(event) {
event.preventDefault();
$(this).doSomething();
}
回答by kamui
I have a simple JS function for that
我有一个简单的 JS 函数
function getEventTarget(event) {
var targetElement = null;
try {
if (typeof event.target != "undefined") {
targetElement = event.target;
}
else {
targetElement = event.srcElement;
}
// just make sure this works as inteneded
if (targetElement != null && targetElement.nodeType && targetElement.parentNode) {
while (targetElement.nodeType == 3 && targetElement.parentNode != null) {
targetElement = targetElement.parentNode;
}
}
} catch (ex) { alert("getEventTarget failed: " + ex); }
return targetElement;
};
in your html
在你的 html
<a href="#" onclick="callme.call(this,event);return false;">foo</a>
in your function
在你的函数中
function callme(event) {
var me = getEventTarget(event); //someway to get the dom element of the a-tag
$('#'+ me.id).toggle();
}
getEventTarget() will bring back the whole dom object which you can manipulate as you please, or has been said already by other users you can just use
getEventTarget() 将带回整个 dom 对象,您可以随意操作,或者其他用户已经说过,您可以直接使用
function callme(event) {
$(this).toggle();
}
回答by Okan Kocyigit
send this
parameter to your function.
将this
参数发送到您的函数。
<a href="#" onclick="callme(this);return false;">foo</a>
function callme(me) {
$(me).toggle();
}
回答by ovnis
better dont use onlcick in html markup
最好不要在 html 标记中使用 onlcick
$(document).ready(function() {
$("a").click(callme);
})
function callme() {
var me = this;
$(me).toggle();
}