2013-01-03 40 views
6

Làm cách nào để có tất cả các liên kết có tiện ích mở rộng tệp .pdf mở trong cửa sổ mới bằng jQuery? Tôi cần phải thay đổi điều này:Tạo bất kỳ liên kết nào với .pdf mở trong cửa sổ mới bằng jQuery?

<a href="domain.com/pdf/parkingmap.pdf">parking map</a> 

Trong thế này:

<a href="domain.com/pdf/parkingmap.pdf" target="_blank">parking map</a> 

Tất cả các tập tin nằm trong thư mục /pdf nếu giúp.

Trả lời

20

Để đạt được điều này, bạn có thể chọn bất kỳ phần tử a nào có thuộc tính href kết thúc bằng .pdf và thêm thuộc tính target="_blank" vào đó. Hãy thử điều này:

$(function() { 
    $('a[href$=".pdf"]').prop('target', '_blank'); 
}); 
+0

'.prop() 'hoặc' .attr() '? – Sablefoste

+0

Có lý do nào bạn đang sử dụng '.prop ('target', '_blank');' thay vì '.attr ('target', '_blank');'? – sircapsalot

+0

@SableFoste '.prop()' –

2

Một cách, giả sử bạn muốn liên kết không kết thúc bằng pdf để mở trong cùng một trang:

$('a').click(
    function(e){ 
     e.preventDefault(); 
     if (this.href.split('.').pop() === 'pdf') { 
      window.open(this.href); 
     } 
     else { 
      window.location = this.href; 
     } 
    }); 
0

jQuery one-liner:

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

Cũng trong vanilla Javascript:

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

Hoặc có thể:

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'); 
    } 
} 

Hãy thử nó ở đây: http://codepen.io/gabssnake/pen/KyJxp

+0

Tại sao downvote? – gabssnake

Các vấn đề liên quan