如何使用jQuery在我的页面中查找谷歌广告

How to find Google ads inside my page using jQuery?

本文关键字:查找 谷歌 何使用 jQuery 我的      更新时间:2023-09-26

我试图在一个html页面中找到所有谷歌广告:

 jQuery( "object" ).each(function (index){
    if (this.id.contains("google")) {
      var h = jQuery(this).height();
      var w = jQuery(this).width();
      console.log("h:" + h + ",w: " + w); 
    }

我得到这个错误:不能调用方法包含未定义的

  1. 有人能解释为什么吗?

  2. 我该如何修复(或以正确的方式进行)?

谢谢。

错误消息为"无法调用未定义的方法包含"。由于您正在调用this.id.contains,这意味着this.id是未定义的,因此,它没有id属性。

Javascript没有.contains()方法。您可以使用.indexOf()

jQuery( "object" ).each(function (index){
    if (this.id.indexOf("google") >= 0)
        var h = jQuery(this).height();
        var w = jQuery(this).width();
        console.log("h:" + h + ",w: " + w); 
    }
});

我在做类似的事情时发现了你的问题:我使用的jquery选择器是这样的:

alert($('[class*="google"]').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="bottomLeaderBoard googleAds">
the content ...
</div>

类可以被替换。。我希望它能有所帮助:)