how to get the caller element in href javascript function?

笑着哭i 提交于 2019-12-04 05:32:58

The real answer here is to change the HTML, which you've said you can't do. I'd push back on that if you can. If you're writing the function, and the function name is in the HTML, how is it you can't change the HTML??

But if you really, really can't, you can update the DOM once it's loaded:

var list = document.querySelectorAll('a[href^="javascript:"]');
var x, link;
for (x = 0; x < list.length; ++x) {
    link = list[x];
    link.onclick = new Function(link.href.substring(11));
    link.href = "javascript:;";
}

Live Copy | Live Source

This is fairly naughty, as it uses the Function constructor (which is very much like eval), but if you trust the source of the HTML, that should be okay.

Or of course, if you don't have to use whatever was in the href to start with, just hook up your event handler in the code above and don't use new Function.

try something like this, use jQuery

just select the link tag with your selector

        $(function(){
            var href = $('a').attr('href');
            href = href.replace('javascript:','');
            $('a').attr('href','#');
            $('a').attr('onclick',href);
        })

This is just workaround solution.

If you have access to the js, you could do something like this:

document.addEventListener('DOMContentLoaded', function(){
    var link = document.querySelectorAll('a');
    link[0].addEventListener('click', function(e){
        console.log(e.target);
    });
});

With this, you would be just not be doing anything with the inline href event and just be appending your own handler.

And if no other answer here works for you because you can't update the DOM after it's loaded (try doing any of them if you want to modify a squarespace lightbox - not saying it's impossible, but...), here's an out of the box thinking:

Sometimes there will be something hinting where the a href is. So you could use it.

<div class="hint current">
    <a href="javascript:handleEvent('.hint')">

In my case, I even knew the hint without needing a parameter, which made things even simpler:

function handleEvent (hint) {
    if(!hint) {
        hint = $("div.current");
    }
    hrefElement = $(hint).find('a[href^=javascript]');
}

This of course will make sense if your DOM is constantly being changed by a script you have no access to.

But even if there is nothing hinting on the a href, you still could do something like this:

<a href="javascript:var x=1;handleEvent(1)">

function handleEvent (uniqueId) {
    hrefElement = $('a[href^=javascript:var x='+uniqueId);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!