Make any link with .pdf open in new window with jQuery?

前端 未结 4 698
野性不改
野性不改 2020-12-10 17:36

How can I have all links with a .pdf file extension open in a new window using jQuery? I need to change this:



        
4条回答
  •  情深已故
    2020-12-10 18:22

    jQuery one-liner :

    $('a[href$=".pdf"]').attr('target','_blank');
    

    Also in vanilla Javascript :

    [].filter.call(document.querySelectorAll('a'), function(a){
        return a.href.match('\\.pdf$') ? a.target = '_blank' : 0;
    });
    

    Or maybe :

    var anchors = document.body.getElementsByTagName('a');
    for (var i = 0; i < anchors.length; i++) {
        if(anchors[i].getAttribute('href').match('\\.pdf$') {
            anchors[i].setAttribute('target', '_blank');
        }
    }
    

    Try it here : http://codepen.io/gabssnake/pen/KyJxp

提交回复
热议问题