简体   繁体   中英

javascript get href when link clicked

Here is my situation. I have some links throughout a website. Some of them look like this:

<a target="_blank" onclick="someFunction()" href="/somFile.pdf">some file</a>

and some look like this:

<a target="_blank" href="/somFile.pdf">some file</a>

All of the links should be calling someFunction() when clicked. The ones that have the call in the onclick attribute are legacy content pages. Newer pages have a jQuery click event attached to them like so:

$(document).ready(function(){
  $('a[href$=".pdf"]').click(function() {
    someFunction();
  });
});

So here's the thing. I can update someFunction(), but I cannot touch the actual links or that jQuery. What I need is to know the href value of the link clicked. I have tried using the following within someFunction() :

var ev = window.event;
origEl = ev.target || ev.srcElement;
console.log(origEl.href);

but this does not work. I also tried console.log(window.event) and get nothing, says it is undefined. Any idea what I'm missing here, or is it basically impossible without passing a reference to it when the function is called?

edit: to be clear, I cannot as a short or even medium term solution edit the call to someFunction() in the onclick or in the jQuery code black, so I cannot for instance change them to someFunction(this) or similar. I'm not sure it is possible to get the href from within someFunction() unless I do that though :(

You don't need anything other than this.href inside of the click callback.

$(document).ready(function()
{    
    function someFunction(foo)
    {
        console.log(foo);
    }

    $('a[href$=".pdf"]').click(function()
    {
        someFunction(this.href);
    });
});

Alternately, you can make this point to the <a> even inside of someFunction , like so:

$(document).ready(function()
{    
    function someFunction()
    {
        console.log(this.href);
        console.log(event);
    }

    $('a[href$=".pdf"]').click(someFunction);
});

or if that doesn't suit you, we can get fancier with Function.apply :

$(document).ready(function()
{    
    function someFunction(event)
    {
        console.log(this.href);
        console.log(event);
    }

    $('a[href$=".pdf"]').click(function (event)
    {
        someFunction.apply(this, event);
    });
});

Here it is in PURE JavaScript

    //assuming links inside of a shared class "link"
    for(var i in document.getElementsByClassName('link')) {
        var link = document.getElementsByClassName('link')[i];

        link.onclick = function(e) { 
            e.preventDefault();

            //using returned e attributes
            window.location = e.srcElement.attributes.href.textContent;     
        } 
    } 

    //tested on Chrome v31 & IE 11
    //not working in Firefox v29
    //to make it work in all browsers use something like:

    if (e.srcElement === undefined){
    //scrElement is undefined in Firefox and textContent is depreciated

      window.location = e.originalTarget.attributes.href.value;
    } else {
      window.location = e.srcElement.attributes.href.textContent;
    }

    //Furthermore; when you setAttribute("key" "value"); 
    //you can access it with the above node link. 
    //So say you want to set an objectId on something     
    //manually and then grab it later; you can use 

    //Chrome & IE
    //srcElement.attributes.objectid.textContent; 

    //Firefox
    //e.originalTarget.attributes.objectid.value;

    //*Note: for some unknown reason the attribute being defined as "objectId" is changed to "objectid" when it's set.

So I let this simmer for a while and I did come up with a short term solution...it's pretty hacky and I feel kinda dirty for doing it but sometimes you just gotta do what you gotta do until you can do what you need to do... anyways, I'm posting my ugly solution here for others who might be backed into a similar corner...

Keep in mind, the only code I'm allowed to touch in OP is the someFunction() function itself. Also, I can add some extra code in the same place as where it located, which is what I have done...

Basically the solution is to make an additional click listener that puts the href value into a variable exposed to the function, and hen wrap the someFunction() code in a small timeout to make sure the new click function can do its thing..

<!-- STUFF I CAN'T TOUCH! (located on-page) -->
<a target="_blank" onclick="someFunction()" href="/somFile.pdf">some file</a>
<a target="_blank" href="/somFile.pdf">some file</a>

<script type='text/javascript'>
$(document).ready(function(){
  $('a[href$=".pdf"]').click(function() {
    someFunction();
  });
});
</script>
<!-- END STUFF I CAN'T TOUCH! -->

/*** STUFF I CAN TOUCH! (located in a script include) ***/
// hackjob!
$(document).ready(function(){
  $('a').click(function() {
    if ($(this).attr('href')) someFunction.href = $(this).attr('href');
  });
});

function someFunction(a) {
  // more hackjob!
  window.setTimeout("console.log(someFunction.href);",200);
}
/*** END STUFF I CAN TOUCH!***/

So anyways, yeah it's ugly, but hopefully it might save someone's arse if they are desperate.

使用this.href或更合适的jQuery $(this).attr('href')来获取每个链接的值。

Here ya go. Try this. Adjust accordingly for your needs (I removed the pdf link because one didn't exist in my fiddle).

EDIT: Tested in FF and Chrome. Let me know if it works for ya.

http://jsfiddle.net/lazerblade01/dTVz5/22/

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