簡體   English   中英

Javascript 獲取 dom 元素 a function 被調用自

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM