0

我需要根据其值更改每个 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...
   }
 }
}

在检查元素上,这种输出。

元素 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 值的类。任何想法?

4

2 回答 2

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...
   }
  }
}
于 2013-11-01T02:57:45.793 回答
0

class 属性映射到className 属性,以免与 ECMCAScript 未来的保留字class发生冲突,因此您需要以下内容:

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';    
  }
}
于 2013-11-01T03:04:15.563 回答