id of a link that a function is called from

守給你的承諾、 提交于 2019-12-13 07:49:31

问题


I hope it's not a problem to post much specific code here, but I figure it will be better explained if everyone can just see it, so I will give you my code and then I will explain my problem.

My code:

function addBeGoneLinks () {
     var beGoneClassElems;
     var beGoneSpan;
     var beGoneLink;
     var beGonePrintSafe;
     var spacesSpan;
     //var middotSpan = document.createElement ('span');

     var interactionContainer = document.getElementsByClassName('feedItemInteractionContainer');

     for (var i=0; i<children.length; i++)
     {
         beGonePrintSafe = false;

         beGoneClassElems = children[i].getElementsByClassName('beGone')

         beGonePrintSafe = true;


         if (beGoneClassElems.length == 0)
         {
             beGoneLink = document.createElement('a');
             beGoneLink.href = 'javascript:void(0);';
             beGoneLink.appendChild(document.createTextNode('Be Gone'));
             beGoneLink.className = 'beGone';
             beGoneLink.id = 'beGoneLink' + i.toString();
             beGoneLink.addEventListener ("click", function() {beGone();}, false);//This line!
             beGoneLink.align = 'right';

             spacesSpan = document.createElement('span');
             spacesSpan.innerHTML = ' - ';

             if (interactionContainer[i] != undefined)
             {
                 interactionContainer[i].appendChild(spacesSpan);
                 interactionContainer[i].appendChild(beGoneLink);
             }
         }
     }
}

Here I have a function from a Greasemonkey script that I am working on. When one of the links is clicked, my aim is to have it call the function beGone() which will, among other things, remove the whole element a few parents up, thereby removing their sibling's, their parents and their parents' siblings, and one or two levels after that.

My idea was just to get the id of the link that was pressed and pass it to beGone() so that I could then get the parents using its id, but I do not know how to do that. Am I able to have the id of a link passed by the function that it calls? If not, is there any other way to do this?

I am not sure whether I am missing some really simple solution, but I haven't been able to find one rooting around the web, especially because I was unsure how I would search for this specific problem.


回答1:


Try this:

beGoneLink.addEventListener("click", beGone, false);

beGone = function (evt) {
    evt.target; // evt.target refers to the clicked element.
       ...
}


You can then use evt.target.id, evt.target.parentNode, etc.



来源:https://stackoverflow.com/questions/14767768/id-of-a-link-that-a-function-is-called-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!