使用 javascript 或 jquery 将多个广告注入页面的有效方法是什么?

What is an efficient method to inject multiple ads into a page using javascript or jquery?

用户可以选择开启广告。如果找到(或没有)cookie,它应该显示广告。我已经能够拼凑出一些似乎有效的东西并做我需要的,但它又丑又笨重。从函数中返回广告代码是我让它正确显示的唯一方法。我可以使用哪些快捷方式来只有一个处理多个广告的主要功能?

我是初学者,请放轻松。任何建议或方向都会很棒。谢谢

    var showadsornot = getAdCode();
  
    // Put strings in array
  var adText = [
    "<h1>Ad Code 1</h1>",
    "<h1>Ad Code 2</h1>",
    "<h1>Ad Code 3</h1>",
    "<h1>Ad Code 4</h1>"
  ];

  // Look in container to get an array of ad elements
  var container = document.getElementById('globalWrapper');
  var ads = container.querySelectorAll('.displayad');

  // For each element insert the string with the same index
  // (i.e. the first string matches the first element, etc.
  Array.from(ads).forEach(function (displayad, index) {
   displayad.innerHTML = writeAdCode(showadsornot, adText[index]);
  });

  function getAdCode() {
   var showadsornot = "1"; // or empty null
   return showadsornot;
  }

  function writeAdCode(showadsornot, adcode) {
   var newAdCodeTwo = "";
   if(showadsornot){
    newAdCodeTwo += adcode;
   } else {
    newAdCodeTwo += "<h2>No Ads For You!</h2>";
   }
   return newAdCodeTwo;
  }
<html>
<head></head>
<body>
<div id="globalWrapper">

 <!-- Ad Code #1 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #2 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #3 -->
 <div class="container">
  <div class="displayad"></div>
 </div>

 <!-- Ad Code #4 -->
 <div class="container">
  <div class="displayad"></div>
 </div>
 
</div>
</body>
</html>

由于您有 4 个相似的元素和相同数量的字符串要插入到这些元素中,因此使用数组会有所帮助。

假设您在这样的容器中构建广告元素:

<div id="ad-container">
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
  <div class="ad"></div>
</div>

这将允许您遍历元素数组并将匹配的文本放入其中。

// First put the strings in an array
var adText = [
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000001'></ins>",
  "<ins class='adsbygoogle' data-ad-format='auto' style='display:block' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000002'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:970px;height:250px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000003'></ins>",
  "<ins class='adsbygoogle' style='display:inline-block;width:300px;height:1050px' data-ad-client='xx-xxx-xxxxxxxxxxxx' data-ad-slot='00000000004'></ins>"
];

// Look into the container to get an array of ad elements
var container = document.getElementById('ad-container');
var ads = container.querySelectorAll('.ad');

// For each of these ad elements insert the string with the same index
// (i.e. the first string matches the first element and so on    
ads.forEach(function (ad, index) {
  ad.innerHTML = writeAdCode(showadsornot, adText[index]);
});

您还可以根据数组中的广告字符串数量,将 'ad' 元素动态添加到空容器中。您只需遍历字符串数组,forEach 字符串创建一个广告元素并插入其文本。