2012-07-10 43 views
3

這個jQuery代碼將在wordpress編輯器中作爲書籤運行。 bookmarklet/jQuery代碼將編輯內容字段中的文本,並將一個參數(例如?參數)附加到URL的末尾。jQuery來識別URL並追加參數

該URL始終是相同的域名(例如domain.com)。但是URL通常會包含目錄(例如domain.com/directory/index.html?parameter)。無論域名後面是什麼,我都需要追加jQuery代碼。

最複雜的情​​況是domain.com/directory/index.html?someotherparameter?parameter。此內容區域通常會包含多個網址,因此腳本需要遍歷整個文本。

我半工作代碼

var url= 'domain.com'; 
var append = ' ?parameter '; 

$(".wp-editor-area").each(
    function(){ 
     var haystack = $(this).text(); 
     $(this).text(haystack.replace(url, url+ append)); 
    }); 

,它正在修改

<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content">&lt;a title="This is a hyperlink" href="http://domain.com/directory"&gt;This is a hyperlink&lt;/a&gt;</textarea></div> 

其電流輸出

<a title="This is a hyperlink" href="http://domain.com ?parameter /directory">This is a hyperlink</a> 

Jsfiddle for convenience

通知的HTML代碼我OU tput不會附加在整個URL之後。如何修改這些更復雜的URL,並在文檔正文中包含更多URls時循環遍歷文檔?

我能找到的唯一相關和類似的問題是this,但是我無法複製結果。

謝謝!

回答

2

首先,the Fiddle

您的示例代碼完全按照您的要求進行操作。它用字段和參數替換了字符串的'domain.com'部分。一旦發現'domain.com'它停止查看是否還有其他附件。

而不是直接文本替換,請嘗試使用a regular expression查找字符串中的URL。

來源:

<div id="wp-content-editor-container" class="wp-editor-container"> 
    <textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"> 
     &lt;a title="This is a hyperlink" href="http://domain.com/directory"&gt;This is a hyperlink&lt;/a&gt; 
     &lt;a title="This is another hyperlink" href="http://google.com/directory"&gt;This is another hyperlink&lt;/a&gt;   
    </textarea> 
</div>​ 

的Javascript:

var url = 'domain.com'; 
var append = '?parameter '; 

$(".wp-editor-area").each(function() { 
    $(this).text(urlify($(this).text())); 
}); 

function urlify(text) { 
    var urlRegex = /(\b(https?|ftp|file):\/\/[domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 
    return text.replace(urlRegex, function(url) { 
     return url + append; 
    }) 
}​ 
+0

謝謝!這幾乎是完美的......但是,我需要的腳本只適用於特定的領域。我將如何使腳本只適用於domain.com而不適用於google.com? – DirkDiggler 2012-07-10 23:39:52

+0

@ user1512806我在我的答案中更新了正則表達式,只根據請求查找特定域中的URL。如果我的答案幫助解決了您的問題,給它一個upvote並將其標記爲接受的答案將幫助其他遇到同樣問題的人找到更快的解決方案。 – 2012-07-11 14:38:34

+0

它的工作原理!非常感謝!我很樂意回覆你的答案,但我沒有足夠的聲望。但是,我將其標記爲正確。再次感謝! – DirkDiggler 2012-07-11 14:58:43