2011-10-07 45 views
0

我正在製作一些鏈接誘餌,它基本上是一個外部託管的.js文件,用戶可以將它們放在他們的網站上。我想要一個隨附的html鏈接隨附小工具,但我希望小部件檢測鏈接是否存在。即JavaScript中的.js文件,檢測是否存在父級鏈接

&lt;script src="http://domain.com/foo.js">&lt;/script><br /> 
by &lt;a href="http://domain.com">My Site&lt;/a> &lt;-- detect this is here 

問題是,我不知道我的小部件將放置在哪個網站上。

有什麼想法?

+0

該鏈接可以使用'display:none'來輕鬆隱藏。如果您確實需要「鏈接誘餌」,請考慮在代碼的活動部分附近添加一個小鏈接。如果有人喜歡你的功能,他們可能會訪問你的網站。 –

回答

0
var l = document.links, myLinkTest = false; 
var linkcount = l.length; 
while(linkcount > 0 && !myLinkTest) { 
    if(l[linkcount-1].href == "http://domain.com"){myLinkTest = true;} 
    linkcount --; 
} 
var widget = function(){ 
    if(myLinkTest){ 
    //do stuff 
    } 
}(); 

測試頁面上的所有鏈接,只有在發現鏈接時才運行腳本功能?

+0

試過這個,並將dostuff改爲document.write('it works');但它不報告成功。 – trooperbill

0

您可以查找所有錨點元素並驗證具有該href的錨點是否存在或使用其他條件進行驗證。

var isMyLinkPresent = function() { 
    var anchors = document.getElementsByTagName('a'); 
    for (i = 0; i < anchors.length; i++) { 
     if(anchors[i].attr('href') === "http://domain.com") { 
      return true; 
     } 
    }; 
    return false; 
} 
//in case you want to notify you own server of the presence, this will send a request to your server for picking up which site actually has the link 
(function() { 
    if (isMyLinkPresent()) { 
     var script = document.createElement('script'); 
     script.attr('src', 'http://domain.com/tellmewhichsitehasit?site=' + window.location.host) 
     document.head.appenChild(script); 
    } 
})(); 

另外,你可以把自己的JavaScript鏈接,但你必須有一些API的網站管理員將使用。在腳本的'src'屬性中,您可以添加參數,然後您可以在生成javascript時選擇它,或者通過查看src來解釋它。

+0

嗨ive試過這個,並刪除'萬一你想...'位並改變返回true;到document.write('works');但它沒有報告成功......任何提示? – trooperbill

+0

你能提供一個你正在執行它的HTML文件的例子嗎? –