jQuery / Javascript用%20替换锚链接中的
我是jQuery的新手,我正在尝试编写一些代码来浏览页面并重写锚链接href属性,以便删除空格并替换为%20。
到目前为止我有:
$(".row a").each(function(){ $(this).attr("href").replace(/\s/g,"%20"); });
我尝试了一些没有运气的变种。
您的方法是正确的,但是一旦替换它就忘记设置新值。 试试这个:
$(".row a").each( function() { this.href = this.href.replace(/\s/g,"%20"); });
你最好使用原生的javascript encodeURI
函数。
$(".row a").each(function(){ $(this).attr( 'href', encodeURI( $(this).attr("href") ) ); });
您必须在代码中设置属性值( attr(key, value)
),只读取其值:
$(".row a").each(function(){ $(this).attr('href', $(this).attr("href").replace(/\s/g,"%20")); });
@Naresh是的,有一种方法,见下面的例子:
编码后解码URI:
上面代码的输出将是:
my%20test.asp?name=st%C3%A5le&car=saab my test.asp?name=ståle&car=saab
有关详细信息,请访问此处
您可以像这样替换""
:
$(document).ready(function () { $("#content a").each(function (){ $(this).attr('href', $(this).attr("href").replace("%20","")); }); });
我知道这是超级晚了,但我发现unescape()
方法也很有用……