用户可以选择开启广告。它应该在找到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>
答案 0 :(得分:1)
由于您有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
字符串创建一个广告元素并插入其文本。