【问题标题】:jQuery: Adding attribute and including href valuejQuery:添加属性并包含 href 值
【发布时间】:2015-03-27 03:58:31
【问题描述】:

我想检查链接是否不包含 URL 的一部分,如果是,请添加“onclick”属性(用于 Analytics 跟踪)。我可以这样做,但不知道如何将实际链接的 href 添加到新属性中。

例如,如果我只想定位不包含“example.com”的链接,我可以这样做:

$('a:not([href*="example.com"])').attr("onclick","_gaq.push(['_trackEvent','clickout-see-also','web','www.blah.com']);");

如何将 'www.blah.com' 替换为实际的 href 值?我猜它与this.href 有关,但无法正常工作...我尝试了以下方法,但得到了undefined

$('a:not([href*="example.com"])').attr("onclick","_gaq.push(['_trackEvent','clickout-see-also','web'," + $(this).attr('href') + "]);");

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: jquery


    【解决方案1】:

    尝试使用.attr()的接收函数来实现你想要的,

    $('a:not([href*="example.com"])').attr("onclick", function(){
      return "_gaq.push(['_trackEvent','clickout-see-also','web','" + $(this).attr('href') + "']);"
    });
    

    【讨论】:

    • @neil 很高兴为您提供帮助。! :)
    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多