【问题标题】:How to use Onclick event in <Script> tag to show a div如何在 <Script> 标签中使用 Onclick 事件来显示 div
【发布时间】:2019-01-21 09:51:57
【问题描述】:

我正在尝试编写代码以在点击任何网站的广告后隐藏和显示&lt;div&gt;。此广告是脚本的结果。那么如何在&lt;script&gt;标签中使用onclick事件呢?

我的代码:

<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

<div class="bnrdiv" onClick="myFunction()">
       <script type="text/javascript">
var ad_idzone = "3265310",
     ad_width = "468",
     ad_height = "60";
</script>
<script type="text/javascript" src="https://ads.exdynsrv.com/ads.js"></script>
<noscript><iframe src="https://syndication.exdynsrv.com/ads-iframe-display.php?idzone=3265310&output=noscript&type=468x60" width="468" height="60" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></noscript>
       </div>

<div id="myDIV">
This is my DIV element.
</div>

【问题讨论】:

  • 您的代码有什么问题? bnrdiv 不是里面有广告的DIV吗?
  • 广告可能有自己的点击处理程序将您链接到他们正在宣传的网站,它可能使用event.stopPropagation(),因此点击事件永远不会冒泡到您的 DIV。

标签: javascript jquery html onclick dom-events


【解决方案1】:

你不能这样做。

广告和浏览器对clickjacking 的防御将在您的代码有机会检测到点击之前消耗点击。


警告:听起来您试图激励人们点击广告(点击广告查看内容),这违反了大多数广告服务的条款和条件。

【讨论】:

    【解决方案2】:

    您可以使用 Jquery 事件 .toggle()

    <!-- Call Jquery libs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <script>
        $(function () {
            // When thue user clicks an ad
            // the .bnrdiv contains the ad
            $('.bnrdiv').click(function () {
                $('#myDIV').toggle();
            });
        });
    </script>
    
    <div class="bnrdiv">
        <script type="text/javascript">
            var ad_idzone = "3265310",
                ad_width = "468",
                ad_height = "60";
        </script>
        <script type="text/javascript" src="https://ads.exdynsrv.com/ads.js"></script>
        <noscript>
            <iframe src="https://syndication.exdynsrv.com/ads-iframe-display.php?idzone=3265310&output=noscript&type=468x60"
                width="468" height="60" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
        </noscript>
    </div>
    
    <div id="myDIV">
        This is my DIV element.
    </div>
    

    【讨论】:

    • 你能重新检查一下吗.. while
    • 您的广告容器 (
      ) 有元素吗?
    • 是的,它有..
      这是我的 DIV。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2017-05-17
    • 2015-05-13
    • 2010-10-29
    • 1970-01-01
    • 2012-07-08
    • 2013-02-22
    相关资源
    最近更新 更多