我有一个简单的 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;
};
在你的 html
<a href="#" onclick="callme.call(this,event);return false;">foo</a>
在你的功能中
function callme(event) {
var me = getEventTarget(event); //someway to get the dom element of the a-tag
$('#'+ me.id).toggle();
}
getEventTarget() 将带回您可以随意操作的整个 dom 对象,或者其他用户已经说过您可以使用
function callme(event) {
$(this).toggle();
}