2014-04-02 18 views
-1

我有下面的代碼追蹤點擊的鏈接,然後將數據輸入到谷歌Analytics(分析):如何檢查是否A HREF鏈接有一個ID或者不

$(document).ready(function(){ 
    $('td.rightImage a').click(function(){ 
    _gaq.push(['_trackEvent', 'rightbanner', 'click', $(this).attr('href'),0,true]); 
    }); 
     }); 

在分鐘我使用的HREF給每個鏈接一個唯一的名字,但一些鏈接有我喜歡使用的ID。如何檢查鏈接是否有ID並使用該ID,但如果鏈接沒有ID,則使用href作爲唯一名稱。

感謝

回答

1

使用.attr('id')

if($(this).attr("id")){ 
    //id exist 
}else{ 
    //id does not exist 
} 
0

您可以使用下面的代碼行找到點擊元素ID

$(this).attr('id') 
0

你可以試用一下這個:

$(document).ready(function(){ 
    $('td.rightImage a').click(function(){ 
      var idHref = (this.id.length) ? this.id : $(this).attr('href'); 
      _gaq.push(['_trackEvent', 'rightbanner', 'click', idHref, 0, true]); 
    }); 
}); 

這種使用三元操作的方式,你可以得到的id偏好,如果不可用,那麼它會採取href。

相關問題