繁体   English   中英

您如何将这两个脚本合而为一?

[英]How could you combine these two scripts into one?

完全不熟悉Javascript。 如果可能,希望将这两个脚本合并为一个:

<script>
(function() {
var link = document.createElement('link');
link.rel = "stylesheet";
link.href = "https://www.example1.com";
document.querySelector("head").appendChild(link);
})();
</script>

<script>
(function() {
var link = document.createElement('link');
link.rel = "stylesheet";
link.href = "https://www.example2.com";
document.querySelector("head").appendChild(link);
})();
</script>

您的代码的类似脚本

<script>
(function(){
   var headUrl = ["https://www.example1.com","https://www.example2.com"];
   headUrl.forEach(function(linkURL) {
      let link = document.createElement('link');
      link.rel = "stylesheet";
      link.href = linkURL;
      document.querySelector("head").appendChild(link);
   })
})()
</script>

仅具有一个函数,并将变量作为参数传递。 您粘贴的两个函数基本上是相同的:

 <script>
    function oneFunction(href){
      var link = document.createElement('link');
      link.rel = "stylesheet";
      link.href = href;
      document.querySelector("head").appendChild(link);
    }
    oneFunction("https://www.example1.com");
    oneFunction("https://www.example2.com");
 </script>
<script>
(function() {
var link1 = document.createElement('link');
var link2 = document.createElement('link');
link1.rel = "stylesheet";
link1.href = "https://www.example1.com";
link2.rel = "stylesheet";
link2.href = "https://www.example2.com";
var head =  document.querySelector("head")
head.appendChild(link1);
head.appendChild(link2);

})();
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM