Bootstrap 如何用javascript将href转换为引导按钮

cwxwcias  于 2023-03-06  发布在  Bootstrap
关注(0)|答案(1)|浏览(148)

我有一个自动生成的表,其中有很多链接,如:

<a href="https:/.../pluginfile.php/...">Some random Text</a>

我希望所有这些链接是一个引导按钮,字体真棒像这样:

<a href = "https:/.../pluginfile.php/..." 
      target = "_blank" 
      class  = "btn btn-outline-primary" >
  <i class="fa fa-download"></i>
</a>

这是我从谷歌上得到的:

let downloadlink = document.querySelectorAll('a[href*="pluginfile.php"]');
   // All Links with ...pluginfile.php...
    
let downloadbutton = document.createElement('a');

// This might also help (from google):

downloadbutton.innerHTML = '<i class="fa fa-download"></i>';

我不知道如何把这些片段拼凑起来,填补缺失的部分。我将感激任何帮助。

gev0vcfq

gev0vcfq1#

只要使用一个循环来遍历所有链接,并在需要时插入/删除/修改。

//Getting <a> tags with href that contains "pluginfile.php"
const targetLinks = document.querySelectorAll(`a[href*="pluginfile.php"]`);

//Loop through targetLinks to target each <a> tag respectively
for(let i=0; i<targetLinks.length ;i++){

  //Get the current <a> tag's content
  const originalContent = targetLinks[i].textContent;
  
  //Setting bootstrap classes
  targetLinks[i].setAttribute("class", "btn btn-outline-primary");
  
  //Setting target action
  targetLinks[i].setAttribute("target", "_blank");
  
  //Adding fontAwesome Icon and the original content
  //You may remove ${originalContent} from below code if you dont need to remain the content
  targetLinks[i].innerHTML = `<i class="fa fa-download"></i>${originalContent}`
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<a href="https://first/pluginfile.php/...">Random Text A</a>
<a href="https://second/pluginfile.php/...">Random Text B</a>
<a href="https://third/pluginfile.php/...">Random Text C</a>
<a href="https://forth/pluginfile.php/...">Random Text D</a>
<a href="https://fifth/pluginfile.php/...">Random Text E</a>
<a href="https://sixth/pluginfile.php/...">Random Text F</a>
<a href="https://seventh/pluginfile.php/...">Random Text G</a>
<a href="https://eighth/pluginfile.php/...">Random Text H</a>
<a href="https://ninth/pluginfile.php/...">Random Text I</a>
<a href="https://tenth/pluginfile.php/...">Random Text J</a>
<a href="https://google.com">This should not be bootstrapped 1</a>
<a href="https://example.org">This should not be bootstrapped 2</a>
<a href="https://example.net">This should not be bootstrapped 3</a>

相关问题