2013-04-08 9 views
7

ファイルへのリンクがあるサイトのリストに動的に入力されたリンクがあります。 jQueryを使用して、ファイルの名前が.pdfで終わるかどうかを確認し、リンクテキストが.mp3で終わる場合はhrefなどにクラスを追加できますか?jQueryリンクに特定のテキストが含まれている場合、hrefにクラスを追加します。

例えば、私は私のリストで、次のリンクを持っている:

  • Document1.pdf
  • Song1.mp3
  • Song2.m4a
  • Document2.doc

私は考え最後の文字を検出してリンクに別のクラスを追加すると、Document1.pdfというテキストのリンクには、クラスが追加されますをアンカー要素に、テキストSong1.mp3とのリンクにアンカー要素にクラスmp3を追加します。

$('a[href$=".mp3"]')... 

オプション:追加情報については、

 
    Attribute Contains Prefix Selector [name|="value"] 
    Selects elements that have the specified attribute with a value 
    either equal to a given string or starting with that string followed 
    by a hyphen (-). 

    Attribute Contains Selector [name*="value"] 
    Selects elements that have the specified attribute with a 
    value containing the a given substring. 

    Attribute Contains Word Selector [name~="value"] 
    Selects elements that have the specified attribute with a value 
    containing a given word, delimited by spaces. 

    Attribute Ends With Selector [name$="value"] 
    Selects elements that have the specified attribute with a 
    value ending exactly with a given string. The comparison is case sensitive. 

    Attribute Equals Selector [name="value"] 
    Selects elements that have the specified attribute with a 
    value exactly equal to a certain value. 

    Attribute Not Equal Selector [name!="value"] 
    Select elements that either don’t have the specified attribute, 
    or do have the specified attribute but not with a certain value. 

    Attribute Starts With Selector [name^="value"] 
    Selects elements that have the specified attribute with a 
    value beginning exactly with a given string. 

    Has Attribute Selector [name] 
    Selects elements that have the specified attribute, with any value. 

    Multiple Attribute Selector [name="value"][name2="value2"] 
    Matches elements that match all of the specified attribute filters. 

Check out the API

答えて

35

は、属性セレクタを使用してください。あなたのようなすべてのリンク与え

-1
$('a[href$=".mp3"]').addClass("mp3"); 
$('a[href$=".pdf"]').addClass("pdf"); 
+0

のErm、おそらく二番目は – Eoin

+0

'$( '[hrefのを言う必要があります$ = "。pdf"] ')。addClass( "pdf"); ' – Eoin

+0

編集されました、ありがとうございます。 – Aioros

1

は、このコードはexts、アレイ内のファイル拡張子を持つすべてのこのようなリンクに拡張クラスを追加するクラス.file

var exts = ['pdf','xls']; 
$('a.file').each(function(){ 
    if($(this).attr('href').match(new RegExp('('+exts.join('|')+')'), 'gi')) 
     $(this).addClass($(this).attr('href').match(/\w{3}$/gi)[0]); 
}) 

を持っています。

0

のではなく、ハード、すべてのタイプのコーディング、あなたはまた、自動的にすべてのあなたのリンクのためにこれを行います解決を行うことができます。

var regex = "/\..{3,4}$/"; 
$('a').each(function() { 
    $(this).addClass(regex.match($(this).attr("href"))[0] 
}); 
関連する問題