[英]How to get/find the function being called from a DOM element or variable in javascript or jquery
[英]Javascript get the dom element a function was called from
HTML部分:
<a href="#" onclick="callme();return false;">foo</a>
JS部分:
function callme() {
var me = ?; //someway to get the dom element of the a-tag
$(me).toggle();
}
在 JS 部分,我能以某种方式获得调用此 function 的 a-tag 吗?
我知道我可以将它作为参数传递,但是这个 function 在页面上使用了很多次,我想避免将参数放在任何地方。
谢谢!
由于您使用的是 onclick 属性(错误),因此您必须将其传递给函数。
onclick="callme(this); return false;"
和 js:
function callme(el) {
var $me = $(el);
$me.doSomething();
}
另一种选择是使用 .call() 设置 function 的上下文。
onclick="callme.call(this,event)"
和 js
function callme(event) {
event.preventDefault();
$(this).doSomething();
}
我有一个简单的 JS function
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;
};
在你的 html
<a href="#" onclick="callme.call(this,event);return false;">foo</a>
在你的 function
function callme(event) {
var me = getEventTarget(event); //someway to get the dom element of the a-tag
$('#'+ me.id).toggle();
}
getEventTarget() 将带回整个 dom object ,您可以随意操作,或者其他用户已经说过您可以使用
function callme(event) {
$(this).toggle();
}
this
参数发送到您的 function。
<a href="#" onclick="callme(this);return false;">foo</a>
function callme(me) {
$(me).toggle();
}
最好不要在 html 标记中使用 onlcick
$(document).ready(function() {
$("a").click(callme);
})
function callme() {
var me = this;
$(me).toggle();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.