【问题标题】:javascript get href when link clicked单击链接时javascript获取href
【发布时间】:2012-04-28 07:30:28
【问题描述】:

这是我的情况。我在整个网站上有一些链接。其中一些看起来像这样:

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

有些看起来像这样:

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

点击时所有的链接都应该调用 someFunction()。在 onclick 属性中有调用的是旧内容页面。较新的页面有一个 jQuery click 事件,如下所示:

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

所以事情就是这样。我可以更新 someFunction(),但我无法触及实际的链接或 jQuery。我需要知道点击链接的 href 值。我尝试在 someFunction() 中使用以下内容:

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

但这不起作用。我也试过console.log(window.event) 并没有得到任何东西,说它是未定义的。知道我在这里缺少什么,或者在调用函数时不传递对它的引用基本上是不可能的吗?

编辑:需要明确的是,作为短期甚至中期解决方案,我不能在 onclick 或黑色 jQuery 代码中编辑对 someFunction() 的调用,因此我不能例如将它们更改为 someFunction(this) 或类似的。我不确定是否可以从 someFunction() 中获取 href ,除非我这样做:(

【问题讨论】:

  • 我的小提琴按您的要求工作。我确实必须修改您的代码块,但只是为了防止链接实际尝试获取某些内容,并由于缺少 pdf 参考链接而相应地符合其余代码。

标签: javascript onclick


【解决方案1】:

这里是纯 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.

【讨论】:

    【解决方案2】:

    click 回调中,除了this.href 之外,您不需要任何其他内容。

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

    或者,您可以使this 指向<a>,甚至在someFunction 内部,如下所示:

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

    或者,如果这不适合您,我们可以通过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);
        });
    });
    

    【讨论】:

    • OP说他不能触摸点击功能。他说必须在 javascript 中执行此操作,但无需更改前 2 部分代码。
    • 不完全清楚确切地 jQuery 代码有什么不能改变的。如果什么都不能改变,那就做不成。
    • 对...我无法更改 jQuery 代码块或 onclick 调用中的任何内容.. 所以我不能只做someFunction(this); 另外,我尝试在 someFunction() 和它里面做console.log(this.href);也给了我“未定义”
    • 好吧,无论如何,我给了 +1 的努力,我想我只需要告诉客户吮吸它,在他们做需要做的事情之前没有快乐:/
    • @mysql_noobie_xxxx 所以它与遗留代码一起使用。我每天都这样。
    【解决方案3】:

    所以我让它慢了一会儿,我确实想出了一个短期的解决方案……它很老套,我觉得这样做有点脏,但有时你只需要做你必须做的事情,直到你能做你需要做...无论如何,我在这里发布我丑陋的解决方案,以供其他可能陷入类似困境的人...

    请记住,我可以在 OP 中接触的唯一代码是 someFunction() 函数本身。另外,我可以在它所在的位置添加一些额外的代码,这就是我所做的......

    基本上,解决方案是制作一个额外的点击监听器,将 href 值放入暴露给函数的变量中,然后将 someFunction() 代码包装在一个小的超时中,以确保新的点击函数可以完成它的工作。 .

    <!-- 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!***/
    

    所以无论如何,是的,它很丑陋,但希望它可以拯救绝望的人。

    【讨论】:

    • 好主意。只有两个调整: 1. 将超时减少到 0。你 don't need 200ms 并且你可能会丢失双击。 2.不要将href保存到someFunction.href,只使用共享范围内的变量即可。
    【解决方案4】:

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

    【讨论】:

    • 在这种情况下绝对不需要使用.attr()this.href 适用于所有浏览器,具有更好的性能,并且明显更简洁。 stackoverflow.com/a/4652402/139010
    • @MДΓΓБДLL:我的印象是 IE 的“旧”版本(虽然我不记得 哪个 版本)需要this.getAttribute('href') 而不是简单的@987654327 @?抱歉,我无法为这种理解提供支持,不过……我想这只是我长期以来一直相信的事情之一。 =/
    • @DavidThomas 我可能是错的,因为我使用该答案作为参考,但我自己没有测试过(我在工作和家里运行 OS X,VM 根本不值得努力)。
    • @MДΓΓБДLL:我能说什么? '是一个参考..!虽然我还是很好奇。那么,也许明天的工作。或者……每当我下次想起它时。
    • 我在 someFunction() 中添加了console.log(this.href);,它说'未定义':(
    【解决方案5】:

    给你。尝试这个。根据您的需要进行相应调整(我删除了 pdf 链接,因为我的小提琴中不存在该链接)。

    编辑:在 FF 和 Chrome 中测试。让我知道它是否适合你。

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

    【讨论】:

    • 您好 Lazerblade:我访问了您的链接(使用最新版本的 FF),控制台日志给了我一条错误消息“未定义事件”
    • 是的,我在 Chrome 中测试过。我看看我能不能也去FF工作,给我几分钟。需要调整。
    • AFAIK, window.event 不兼容跨浏览器。我很惊讶它可以在 IE 以外的任何地方使用,我严重怀疑你是否能够在 Firefox 中使用 window.event
    • 不需要。创造性思考。如果由于无法更改而无法在第一段代码中捕获事件,那该怎么办?
    • 完全没有必要为了实现 FF 兼容性而跳的代码,而您仍然更改了 jQuery 事件绑定代码。按照这个速度,您不妨使用我提出的(更简洁的)选项之一。
    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多