2013-11-01 106 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';  
    } 
}