我是新來的jQuery,我想寫一些代碼來瀏覽頁面並重寫錨鏈接href屬性,以便空格被刪除並替換爲%20 。jQuery/Javascript替換<space>與%20的錨點鏈接
到目前爲止,我有:
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
我試過的這幾個變化,沒有運氣。
我是新來的jQuery,我想寫一些代碼來瀏覽頁面並重寫錨鏈接href屬性,以便空格被刪除並替換爲%20 。jQuery/Javascript替換<space>與%20的錨點鏈接
到目前爲止,我有:
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
我試過的這幾個變化,沒有運氣。
您的方法是正確的,但是一旦您替換它,您就會忘記設置新值。試試這個:
$(".row a").each(function() {
this.href = this.href.replace(/\s/g,"%20");
});
必須設置屬性值(attr(key, value)
),在你的代碼只是讀取它的值:
$(".row a").each(function(){
$(this).attr('href', $(this).attr("href").replace(/\s/g,"%20"));
});
你會更好使用本地JavaScript encodeURI
功能。
$(".row a").each(function(){
$(this).attr('href', encodeURI($(this).attr("href")));
});
好東西。之前沒有遇到'encodeURI'。爲我節省了大量的時間。 – 2014-03-08 10:42:02
你可以像這樣代替""
:
$(document).ready(function() {
$("#content a").each(function(){
$(this).attr('href', $(this).attr("href").replace("%20",""));
});
});
@Naresh 是的,有針對的方式,請參見下面的例子:
解碼URI編碼之後:
<script type="text/javascript">
var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br />");
document.write(decodeURI(uri));
</script>
代碼的輸出將是:
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab
更多詳情,請訪問here
我知道這是超級晚了,但我發現unescape()
方法往往也是工作...
只是一個筆記,因爲我打我的頭試圖弄清楚這一點。我使用Firefox的HTML Validator插件,它仍然報告URI引用中的空白。這是因爲驗證器分別解析頁面,*沒有* JavaScript。 – Travis 2009-11-09 17:58:53