单击链接时javascript获取href

标签 javascript onclick

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

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

有些看起来像这样:

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

所有链接在被点击时都应该调用 someFunction()。在 onclick 属性中调用的是遗留内容页面。较新的页面有一个 jQuery 单击事件附加到它们,如下所示:

$(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)什么也得不到,说它是未定义的。知道我在这里遗漏了什么,或者在调用函数时不传递对它的引用基本上是不可能的吗?

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

最佳答案

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

关于单击链接时javascript获取href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183102/

相关文章:

javascript - Outlook中自定义表格标签不兼容问题如何解决

javascript - `req`在nodejs中指的是什么?

android - Rxjava2 查看回收器适配器中的点击次数

android - 单击时如何更改 ImageView 的图像?

javascript - JQuery 1 单击触发 2 个条件(如果)

javascript - 为什么 onClick 函数无法识别?

javascript - 使用ajax在后台删除mysql数据库条目

javascript - 如何在echarts中将条形图放在x轴中心

Firebase 上的 JavaScript : something wrong in once ("value"). then();

javascript - 使用具有 onclick 事件的按钮向按钮添加 onclick 事件?