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

class 属性は、ECMCAScript の将来の予約語classと衝突しないようにclassName プロパティにマップされるため、次のようなものが必要です。

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 に答える
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 に答える