简体   繁体   English

如何使用document.getElementById()添加广告?

[英]How to add an ad using document.getElementById()?

I have a with an id of "ad". 我的ID为“ ad”。 I am trying to put in an adsense ad in there using JavaScript when a user meets a condition. 当用户满足条件时,我正在尝试使用JavaScript在此处投放adsense广告。 Basically when a user meets a certain condition, ads will be shown. 基本上,当用户满足特定条件时,就会展示广告。

This is my code: 这是我的代码:

if ($resultTot = $db->query($queryTot)) 
    {
        $data = $resultTot->fetch_assoc();

     if($data["total"]>1)
        {
                echo "<script>
                    document.getElementById('ad').innerHTML = 'async src='//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'
<!-- YC2 ads -->
<ins class='adsbygoogle'
     style='display:block'
     data-ad-client='ca-pub-4557496244647182'
     data-ad-slot='4151529047'
     data-ad-format='auto'></ins>

(adsbygoogle = window.adsbygoogle || []).push({});

                </script>";


     }
  }

When I use document.getElementId() to change let's say ap tag, it works. 当我使用document.getElementId()进行更改时,假设使用ap标签,它可以工作。 I just can't get the adsense to display. 我只是无法显示adsense。 Any ideas on how I can add it in there and why my code isn't working? 关于如何在其中添加代码以及为什么我的代码无法正常工作的任何想法?

You just need to print regular AdSense JS code. 您只需要打印常规的AdSense JS代码。 No need to get any elements with JS. 无需使用JS获取任何元素。

Currently you are just editing contents of #ad DOM element. 当前,您正在编辑#ad DOM元素的内容。 This dosen't work, because it has to be <script> and not inside of it. 这行不通,因为它必须是<script>而不是它的内部。 src is attribute. src是属性。

It must end up like this 它必须这样结束

<script async src='//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'></script>

So, use this: 因此,使用此:

if ($resultTot = $db->query($queryTot)) 
{
  $data = $resultTot->fetch_assoc();

  if($data["total"]>1)
  {
    echo "
    <div id='ad'>
      <!-- YC2 ads -->
      <ins class='adsbygoogle'
           style='display:block'
           data-ad-client='ca-pub-4557496244647182'
           data-ad-slot='4151529047'
           data-ad-format='auto'></ins>
      <script>
      (adsbygoogle = window.adsbygoogle || []).push({});
      </script>
    </div>
    <script>
      var script = document.createElement('script');
      script.async = true;
      script.src = '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
      document.getElementById('ad').appendChild(script);
    </script>
    ";
  }
}

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

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