简体   繁体   中英

Javascript get the dom element a function was called from

HTML part:

<a href="#" onclick="callme();return false;">foo</a>

JS part:

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?

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!

Since you are using an onclick attribute (BAD.) you have to pass that into the function.

onclick="callme(this); return false;"

and the js:

function callme(el) {
  var $me = $(el);
  $me.doSomething();
}

Another option is to set the context of the function using.call().

onclick="callme.call(this,event)"

and the js

function callme(event) {
    event.preventDefault();
    $(this).doSomething();
}

I have a simple JS function for that

 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

 <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

 function callme(event) {
      $(this).toggle();
 }

send this parameter to your function.

<a href="#" onclick="callme(this);return false;">foo</a>

function callme(me) {
  $(me).toggle();
}

better dont use onlcick in html markup

$(document).ready(function() {
  $("a").click(callme);
})

function callme() {
  var me = this;
  $(me).toggle();
}

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