是否可以通过超链接执行javascript

时间:2017-07-31 12:00:07

标签: javascript html

我有一个链接:

<a href ... /a>

现在,我想在按下上面的超链接时执行javascript,而不在<id>内添加任何代码。

这可能吗?

修改

此问题与之前提出的问题不同,因为我<a href ... /a>内没有任何<a href ... /a>

另外,我无法在merge into work_order_coding_tab A using work_order_coding B on (A.WO_NO = B.WO_NO AND A.ROW_NO=B.ROW_NO) when matched then update set A.amount = B.sales_price_amount where A.WO_NO = B.WO_NO AND A.ROW_NO=B.ROW_NO AND B.work_order_cost_type_db = 'M' AND B.order_no IS NULL AND B.catalog_no IS NOT NULL AND A.amount is not null and A.amount <> B.sales_price_amount and B.contract like 'TZ%' and abc.active_separate_api.get_line_no(B.wo_no) =2 AND A.WO_NO=2002 AND A.ROW_NO=3921; 内添加内联代码。我不知何故需要跟踪超链接的新闻,然后执行javascript。此外,我有很多这样的超链接,我需要以不同的方式跟踪它们。

3 个答案:

答案 0 :(得分:3)

内联:

<a href="https://stackoverflow.com" onclick="return myFunction();">link</a>

<script type="text/javascript">
    function myFunction () {
        // return false => does not navigate to href
        // return true => navigate to href
    }
</script>

或者通过JS添加点击监听器:

var link = document.querySelector('a');
link.onclick = function() {

}

编辑:如果有多个链接:

var links = document.querySelectorAll('a');
for(var i = 0; i < links.length; i++) {
    var link = links[i];
    link.onclick = function() {

    }
}

EDIT2 :如果您想通过 href 属性内容进行区分:

a[href]        an a element with a "href" attribute (CSS 2)
a[href="bar"]  an a element whose "href" attribute value is exactly equal to "bar" (CSS 2)
a[href~="bar"] an a element whose "href" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar" (CSS 2)
a[href^="bar"] an a element whose "href" attribute value begins exactly with the string "bar" (CSS 3)
a[href$="bar"] an a element whose "href" attribute value ends exactly with the string "bar" (CSS 3)
a[href*="bar"] an a element whose "href" attribute value contains the substring "bar" (CSS 3)
a[href|="en"]  an a element whose "href" attribute has a hyphen-separated list of values beginning (from the left) with "en" (CSS 2)

所以你会:

var link = document.querySelector('a[href="theValueIamLookingFor"]');
link.onclick = function() {

}

EDIT3 :您还可以测试for循环中的 href 值:

var links = document.querySelectorAll('a');
for(var i = 0; i < links.length; i++) {
    var link = links[i];
    link.onclick = function() {
        switch(link.href) {
            case 'www.google.com':
                // Do something
                break;
            case 'https://stackoverflow.com':
                // Do something else
                break;
            default:
                return true;
        }
    }
}

答案 1 :(得分:0)

正如您在评论中所说,您的文档中可能有多个标记,最简单的方法是选择具有特定href的元素。

$('a[href^="https://somelink.com"]').click(function() {
    alert('you pressed me');
});

您不需要编辑或添加某些内容即可。&#39; a&#39;标签

答案 2 :(得分:-1)

如果您知道href属性中传递的值,则可以执行以下操作:

修改

$( "a" ).each(function(){
  if($(this).attr("href") === "https://google.com" )
    console.log('hey');
});