【问题标题】:Transforming href links on pageload using jquery使用 jquery 在页面加载时转换超链接
【发布时间】:2014-06-11 10:38:39
【问题描述】:
我需要将所有链接(href 值)转换为特定格式
例如 - 如果页面有链接 http://www.exampledomain.com 我想将其 href 转换为 http://url.com/xyz?http://www.example.com
以下是我用于此任务的 jquery(请注意,我是 jquery 新手)
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
});
});
但上面的脚本正在转换网站的所有链接,我的导航链接也发生了变化。 我们如何过滤以仅更改包含“http”和“www”的链接的 href?
我知道某种正则表达式可以用于此目的。提前致谢!
【问题讨论】:
标签:
javascript
jquery
html
regex
【解决方案1】:
你可以试试下面的代码
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.match("http://www.*"))
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});
你必须确保没有导航链接包含
"http://www"
在其中。在您不想替换 href 的地方使用相对链接。
或者你可以给你想要相应修改的所有锚标签一个类
【解决方案2】:
Demo Fiddle
使用元素检查器检查锚标签的 href
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
使用window.location.host 和test
修改自 CSS-Tricks.com 上的 this article
【解决方案3】:
一种方法:
// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
// i: the index of the current element in the returned collection,
// oldhref: the value of the 'href' before manipulation by the function.
// if 'exampledomain.com' features in the hostname of the link we
// manipulate the 'href' as required, otherwise we simply set the 'href'
// to its original value:
return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});
JS Fiddle demo.
参考资料:
【解决方案4】:
我认为你应该提取所有内部链接。
您可以检查值是否符合您的条件 (http://www):
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.indexOf("http:\\www") > -1 ){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
但是最好把所有的内部链接都提取出来:
var myHost = new RegExp(location.host);
$('a').each(function(){
var value = $(this).attr('href');
if(!(myHost.test(value))){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
最后一个更好的选择是只使用外部链接:(如果你不需要对内部做任何事情)
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
【解决方案5】:
您可以检查链接是外部的还是内部的,然后您可以添加额外的工作。
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if($(this[href^='http'])
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});