2013-11-01 61 views
0

我需要根據其值更改每個href項的類。 我有這個代碼。更改每個標籤中取決於href值的類名

<body onload="myFunction()"> 

    <div class="indi-download"> 
     <div class="pull-left"> 
    <h6 class="file" id="file-display-id">%file_display_name%</h6> 
    </div> 

    <div class="pull-right"> 
     <a class="download-link" id="download_link" href="%file_url%">Download</a> 
    </div> 

    </div> 
</body> 

在獲得類下載鏈接上的href項目時,我使用了這個javascript代碼。

function myFunction() 
{ 
    var anchors = document.querySelectorAll('a.download-link'); 
    for (var i = 0; i < anchors.length; i++) { 
    var url = anchors[i].href; 
    var splitfile = url.split('.').pop(); 
    if(splitfile=='pdf'){ 
     //class="file" would be class="pdf-file" 
    }else if(splitfile=="docx"){ 
     //class="file" would be class="docx-file" 
    }else{ 
     //other file format... 
    } 
} 
} 

on Inspect Element,Something such kind of output。

元1 ---

<div class="indi-download"> 
<div class="pull-left"> 
      //Changed into pdf-file 
    <h6 class="pdf-file" id="file-display-id">Sample PDF 1</h6> 
</div> 
<div class="pull-right"> 
    <a class="download-link" id="download_link" href="http://mysite- 
      info/download/files/file1.pdf">Download</a> 
</div> 
</div> 

元2 ---

<div class="indi-download"> 
<div class="pull-left"> 
      //Changed into docx-file 
    <h6 class="docx-file" id="file-display-id">Sample docx 1</h6> 
</div> 
<div class="pull-right"> 
    <a class="download-link" id="download_link" href="http://mysite- 
    info/download/files/file2.docx">Download</a> 
</div> 
</div> 

如何實現這種輸出的?更改依賴於href上的值的類。任何想法?

回答

0

如果你可以使用jQuery,我覺得這樣的事情應該工作:

function myFunction() 
{ 
    var anchors = document.querySelectorAll('a.download-link'); 
    for (var i = 0; i < anchors.length; i++) { 
    var url = anchors[i].href; 
    var splitfile = url.split('.').pop(); 
    if(splitfile=='pdf'){ 
     $(anchors[i]).removeClass('file'); 
     $(anchors[i].addClass('pdf-file'); 
    }else if(splitfile=="docx"){ 
     $(anchors[i]).removeClass('file'); 
     $(anchors[i]).addClass('docx-file'); 
    }else{ 
     //other file format... 
    } 
    } 
} 
0

屬性映射到的className財產以免與ECMCAScript交鋒未來保留字,所以你想要類似的東西:

anchors[i].className = 'docx-file';. 

適用於你的榜樣,你可以這樣做:

var classNames = {pdf:'pdf-file', docx:'docx-file'}; 
... 
anchors[i].className = classNames[splitfile]; 

,並以適應默認:

anchors[i].className = classNames[splitfile] || 'default-class'; 

以防萬一splitfile不匹配預期值之一。整個功能是:

function myFunction() { 
    var anchors = document.querySelectorAll('a.download-link'); 
    var classNames = {pdf:'pdf-file', docx:'docx-file'}; 

    for (var i = 0; i < anchors.length; i++) { 
    var url = anchors[i].href; 
    var splitfile = url.split('.').pop(); 
    anchors[i].className = classNames[splitfile] || 'default-class';  
    } 
}