2016-11-08 2 views
4

私が使用してjQueryの中でさまざまなファイルの種類が含まれているリンクをターゲットにしています:"a"タグを選択するにはjQueryを使用してhrefに特定のファイルタイプがありますか?

jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=".ods"], a[href$=".txt"], a[href$=".rtf"]').before('<span class="glyphicon glyphicon-file"></span> '); 

まず、繰り返しを削減する方法はありますか?例えば

jQuery('a[href$=".pdf|.doc|.docx"]) 

第2に、ファイル拡張子の異なるケースをターゲットにする方法があります。 Pdf,PDFおよびpdf

答えて

7

.filter()を使用して、選択した要素をフィルタリングできます。 String.prototype.match()の正規表現を使ってフィルタ関数のチェックを拡張しています。

$("a").filter(function(){ 
    return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i); 
}).before("Some html"); 

なお鈍感正規表現一致ケースの端にiフラグ。

+0

をサポートする必要がある場合、いくつかのエスケープを追加する必要があります。/\を実行します。正規表現ではファイル拡張子のみを対象としていますか? – user2726041

+0

@ user2726041いいえ、javascriptの正規表現は '/'の間に設定する必要があります。 '\ .'もマッチします。 – Mohammad

0

単純にCSSを使用するのではなく、custom selectorを作成することができます。

jQuery.expr[':'].hrefEndsWith = function(
     objNode, 
     intStackIndex, 
     arrProperties, 
     arrNodeStack 
     ){ 
     // The list of arguments gets passed as a string - 
     var arrArguments = arrProperties.split(','); 
     // Create a jQuery version of this node. 
     var jThis = $(objNode); 
     // Check to see if this node ends with (we only need to find 
     // one of the titles to qualify). 
     for (var i = 0 ; i < arrArguments.length ; i++){ 
      // Check for title equality. 
      if (jThis.attr("href").endsWith(arrArguments[i])){ 
       // We found a href match, return true to 
       // indicate that this node should be included 
       // in the returned jQuery stack. 
       return true ; 
      } 
     } 
     // If we have made it this far, then we found no 
     // match. Return false to indicate that this node 
     // did not match our selector. 
     return false ; 
    } 

    // Use it 
    jQuery("a:hrefEndsWith('.pdf', '.txt', '.xls')"); 

また、すべてを必要としない場合は、セレクタを作成するためのJS関数を記述することもできます。

function getEndsWithSelector(names) { 
    return names.map(n => 'a[href$=".'+name+'"]').join(); 
} 

jQuery(getEndsWithSelector('pdf', 'txt', 'xls')) 

あなたはあなたに感謝優れた特殊文字

関連する問題