2010-03-04 14 views
1

好吧,基本上,我有這個JavaScript文件http://assets.revback.com/scripts/share1.js,基本上通過JavaScript添加了一堆共享按鈕。如何使這個鏈接工作在javascript

我想要做的,就是改變Twitter圖片鏈接使用的URL縮短:

所以不是:

<a href=\"http:\/\/twitter.com\/home?status=Interesting Post:(UURRLL)\" title=\"Click to share this page on Twitter\"><img src=\"http:\/\/assets.revback.com\/scripts\/images\/twitter.png\" border=\"0\"\/><\/a> 

我想用

<a href="#" onClick="window.location='http://ko.ly?action=shorten&uri=' + window.location + '&dest=twitter.com/?status=Reading ';"><img src=http://assets.revback.com/scripts/images/twitter.png"><\/a> 

,但我需要最底層的,用javascript友好的語法編寫。即像在上面的一個,而不是http://,你有HTTP://

+0

你在問什麼? – SLaks 2010-03-04 17:23:55

+0

基本上我通過JavaScript插入到現有頁面的鏈接,所以我需要解析該底部鏈接,以使其對javascript友好。你知道做一些事情,比如讓所有的/ be \/ – Andrew 2010-03-04 17:26:30

+0

你誤解了字符串文字。你能告訴我們你的代碼嗎? – SLaks 2010-03-04 17:30:45

回答

0

試試這個

<a href="#" onClick="window.location='http://site.com?action=shorten&uri='+ 
    window.location + '&dest=twitter.com/?status=Reading;'">tweet this</a> 
0

變化在onclick屬性鏈接的href

<a href="#" onclick="this.href='http://site.com?action=shorten&uri=' + window.location + '&dest=twitter.com/?status=Reading';">tweet this</a> 

默認操作(進入由href屬性指定的頁面)將始終執行,除非事件處理程序onclick收到返回值false。因此,在發生錯誤之前更改href會使其轉到您希望的頁面,只要您不返回false即可。

1

失去onclick。沒有任何好處,因爲它只是像一個正常的鏈接(除了更多的破碎)。現在您不必擔心JavaScript內部的JavaScript轉義以及隨之而來的瘋狂。

var buttonhtml= (
    '<a href="http://ko.ly?action=shorten&amp;uri='+encodeURIComponent(location.href)+'&amp;dest=twitter.com/?status=Reading">'+ 
     '<img src=http://assets.revback.com/scripts/images/twitter.png">'+ 
    '</a>' 
); 

(注意encodeURIComponent,這是正確插入您目前的網址到另一個網址不會破壞,也保護您免受HTML注入,因爲<必要的,&字符得到%編碼過的。如果沒有保障,包含腳本的任何頁面都存在跨站點腳本漏洞。)

更好的是,完全丟失HTML字符串並使用DOM方法創建您的內容。那麼你不需要擔心&amp;和其他HTML轉義,並且你不需要將你的HTML與原始的,不可靠的字符串替換一起破解。您似乎在使用jQuery,因此:

var link= $('<a>', {href:'http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading'}); 
link.append('<img>', {src: 'http://assets.revback.com/scripts/images/twitter.png'}); 
link.appendTo(mydiv); 

ETA:我會用循環替換整個markuppy混亂,並將數據拆分爲查找。即。例如:

(function() { 
    var u= encodeURIComponent(location.href); 
    var t= encodeURIComponent(document.title); 
    var services= { 
     Facebook: 'http://www.facebook.com/sharer.php?u='+u, 
     Twitter: 'http://ko.ly?action=shorten&uri='+u+'&dest=twitter.com/?status=Reading', 
     StumbleUpon: 'http://www.stumbleupon.com\/submit?url='+u+'&title='+t, 
     // several more 
    }; 

    var share= $('<div class="ea_share"><h4>Share this with others!</h4></div>'); 
    for (var s in services) { 
     share.append($('<a>').attr('href', services[s]).attr('title', 'Click to share this on '+s).append(
      $('<img>').attr('src', 'http://assets.styleguidence.com/scripts/images/'+s.toLowerCase()+'.png') 
     )); 
    } 
    $('#question .vt').append(share); 
})(); 
+0

我在哪裏將該代碼放在我的代碼中以使其工作?當談到JavaScript時,我是一個完整的noob,基本上只是從20個不同的源頭串起原始文件。 – Andrew 2010-03-04 18:48:29