代码之家  ›  专栏  ›  技术社区  ›  jerrygarciuh

访问锚点属性和event.prventDefault()

  •  1
  • jerrygarciuh  · 技术社区  · 12 年前

    我想在不使用旋转栅门的情况下捕捉链接点击并存储在我的数据库中。当前代码

    $( ".ads-box a" ).click(function( event ) {
      event.preventDefault();
      var href = $(this).find('a').attr('href');
      var id = $(this).find('a').attr('id')
      console.log(href);
      console.log(id);
      console.log(this);
    });
    

    <div class="ads-box" id="adbox-35"><a href="http://www.makeitrightnola.org" id="ad-35" target="_blank"><img src="/g/shows/sidebar/83172823_ad_image.png" alt="Make It Right"></a></div>
    

    在控制台中生成

    undefined
    undefined
    <a href="http://www.makeitrightnola.org" id="ad-35" target="_blank"><img src="/g/shows/sidebar/83172823_ad_image.png" alt="Make It Right"></a>
    

    如何访问链接的属性?出了什么问题?

    1 回复  |  直到 12 年前
        1
  •  1
  •   Sergio    12 年前

    移除 .find('a') 在里面 var href = $(this).find('a').attr('href'); 。您已经在 <a> 元素,这样就足够了 $(this).attr('href');

    试试这个:

    $( ".ads-box a" ).click(function( event ) {
      event.preventDefault();
      var href = this.href;  // i used vanilla JS here
      var id = this.id;      // i used vanilla JS here
      console.log(href);
      console.log(id);
      console.log(this);
    });
    

    演示 here