2009-05-12 66 views
9

我是新来的jQuery,我想写一些代码来浏览页面并重写锚链接href属性,以便空格被删除并替换为%20 。jQuery/Javascript替换<space>与%20的锚点链接

到目前为止,我有:

$(".row a").each(function(){ 
    $(this).attr("href").replace(/\s/g,"%20"); 
}); 

我试过的这几个变化,没有运气。

回答

17

您的方法是正确的,但是一旦您替换它,您就会忘记设置新值。试试这个:

$(".row a").each(function() { 
    this.href = this.href.replace(/\s/g,"%20"); 
}); 
+1

只是一个笔记,因为我打我的头试图弄清楚这一点。我使用Firefox的HTML Validator插件,它仍然报告URI引用中的空白。这是因为验证器分别解析页面,*没有* JavaScript。 – Travis 2009-11-09 17:58:53

3

必须设置属性值(attr(key, value)),在你的代码只是读取它的值:

$(".row a").each(function(){ 
    $(this).attr('href', $(this).attr("href").replace(/\s/g,"%20")); 
}); 
20

你会更好使用本地JavaScript encodeURI功能。

$(".row a").each(function(){ 
    $(this).attr('href', encodeURI($(this).attr("href"))); 
}); 
+0

好东西。之前没有遇到'encodeURI'。为我节省了大量的时间。 – 2014-03-08 10:42:02

0

你可以像这样代替""

$(document).ready(function() { 
    $("#content a").each(function(){ 
     $(this).attr('href', $(this).attr("href").replace("%20","")); 
    }); 
}); 
1

@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

0

我知道这是超级晚了,但我发现unescape()方法往往也是工作...