在窗口上添加click事件,但忽略所有以https开头的链接

Add click event on window, but ignore all links that start with https

本文关键字:https 开头 链接 添加 窗口 click 事件      更新时间:2023-09-26

我想在窗口上添加点击事件,但要排除所有以https开始的链接。我尝试了一些方法,但我不确定该往哪个方向走。例如

$(window).not("a[href^='https']").click(function(){
    console.log('Clicked');    
});  

$(window).click(function(evt){
    //somehow check click argument to inspect outgoing URL maybe?        
});    

试试这样:

$(window).on('click', 'a', function(evt){
    if(this.href.indexOf('https') == 0)
        return;
    //other logic here
});  

on方法,我将事件附加到窗口,但它只有在与a选择器匹配的元素上执行时才会触发。然后我检查元素href属性,看看它是否以https开始,如果是,我退出早期。

你可以使用e.stopPropagation(),因为你已经阻止了点击链接时的父点击事件

$(window).click(function(){
    console.log('Clicked');    
})
$("a[href^='https']").click(function(e){
    e.stopPropagation();
    console.log('This was a link');    
})

可以使用window.location.protocol:

$(window).click(function(evt){
    if (window.location.protocol != "https:"){
      alert("clicked but not https");
    }
    else{
      alert("clicked and yes https");
    }
});

jsfiddle here: http://jsfiddle.net/fn4Lk263/