【发布时间】:2010-10-25 15:00:08
【问题描述】:
我是 jQuery 新手,我正在尝试编写一些代码来浏览页面并重写锚链接 href 属性,以便删除空格并替换为 %20。
到目前为止我有:
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
我已经尝试了一些变体,但都没有运气。
【问题讨论】:
标签: javascript jquery html replace
我是 jQuery 新手,我正在尝试编写一些代码来浏览页面并重写锚链接 href 属性,以便删除空格并替换为 %20。
到目前为止我有:
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
我已经尝试了一些变体,但都没有运气。
【问题讨论】:
标签: javascript jquery html replace
最好使用原生 javascript encodeURI 函数。
$(".row a").each(function(){
$(this).attr( 'href', encodeURI( $(this).attr("href") ) );
});
【讨论】:
encodeURI。为我节省了大量时间。
您的方法是正确的,但您在替换后忘记设置新值。试试这个:
$(".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"));
});
【讨论】:
@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
【讨论】:
你可以像这样替换"":
$(document).ready(function () {
$("#content a").each(function (){
$(this).attr('href', $(this).attr("href").replace("%20",""));
});
});
【讨论】:
我知道这已经很晚了,但我发现unescape() 方法也很有效......
【讨论】:
在 ES2021 中使用 replaceAll()
$(".row a").each( function() {
this.href = this.href.replaceAll('',"%20");
});
【讨论】: