2012-02-03 12 views
0

私は、そこにいくつかのリンクを持つhtmlページを持っています。いくつかのリンクは.pdfに接続します。どのようにhtmlページにPDFを含むリンクを見つけてリンクの先頭に絶対パスを付けることができますか?

は、ページのロード時にjavascriptの書き込みが可能です -

  • それは

  • を.PDFにリンクされているすべてのリンクをhtmlファイルをスキャンし、検索しますが、フロントを追加そのハードコードされたフロントエンドとそのURLの?

このページのすべてのリンクは相対的なもので、これらの.pdfリンクがアンドロイドタブレットにプルアップされているときに問題が発生しています。しかし、私が絶対パスを使用すると、それは問題なく処理されます。だから私はちょうど.pdfリンクに絶対パスを追加したい。

答えて

2

あなたはjQueryのを使用している場合は、ここではそれらのすべてのリンクを選択する簡単な方法があります:

$('a[href$=".pdf"]').each(function() { 
    this.href = 'YOUR URL HERE' + this.href; 
}); 

hrefは属性セレクタで、$=「は、それはすなわち、end with the given value属性を検索することを意味します。 pdf」を参照してください。あなたはjQueryのを使用しない場合、あなたはそのように、標準のJavaScriptでそれを行うことができます

var links = document.getElementsByTagName('a'); 

for (var i = 0; i < links.length; i++) { 
    if (links[i].href.substr(links[i].href.length - 4) == '.pdf') { 
     links[i].href = 'YOUR URL HERE' + links[i].href; 
    } 
} 
1

voithosと同じですが、jQueryのなし:機能で

var links=document.links; //Get all links in the document 

for (var i=0;i<links.length;i++) { //Loop through each link 
    thisHrefExt=links[i].href.split("."); //Split target at all periods 
    thisHrefExt=thisHrefExt[thisHrefExt.length-1]; //Select the last section, which should be the extension 

    if (thisHrefExt.toLowerCase()=="pdf") { //If the extension is "pdf" (case insensitive)... 
     links[i].href="hard-coded-front-end"+links[i].href; //...Add your hard-coded bit at the beginning 
    } 
} 

形式:

01:機能付き

function changePDFLinks() { 
    var links=document.links; //Get all links in the document 

    for (var i=0;i<links.length;i++) { //Loop through each link 
     thisHrefExt=links[i].href.split("."); //Split target at all periods 
     thisHrefExt=thisHrefExt[thisHrefExt.length-1]; //Select the last section, which should be the extension 

     if (thisHrefExt.toLowerCase()=="pdf") { //If the extension is "pdf" (case insensitive)... 
      links[i].href="hard-coded-front-end"+links[i].href; //...Add your hard-coded bit at the beginning 
     } 
    } 
} 

、あなたはこのような何かを行うことができます

window.onload=changePDFLinks; 

ページが読み込まれたときにPDFリンクを修正します。

+0

これは素晴らしいです。これを.jsファイルに入れて、それを複数のファイルで実行できるようにすることはできますか? –

+0

確かに、機能フォーム(編集された回答)onloadを使用してください。 –

関連する問題