我需要根据每个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>在获取类download-link上的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...
}
}
}在Inspect元素上,类似这样的输出。
元素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上的值的类。有什么想法吗?
发布于 2013-11-01 10:57:46
如果你可以使用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-01 11:04:16
类属性被映射到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';以防拆分文件与预期值不匹配。整个函数是:
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';
}
}https://stackoverflow.com/questions/19720009
复制相似问题