这个脚本:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if ("a:not(http://)") {
$(this).attr('href', '/' + href);
}
});
});
将斜杠添加到每个链接甚至包含“http://”的链接不知道为什么?我没有收到任何错误?
关于如何解决此问题的任何想法?
答案 0 :(得分:6)
你混淆了两件事:
jQuery选择器:
$(function() {
$('a:not([href^="http://"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
和纯javascript if
语句:
$('a').each(function() {
var href = $(this).attr('href');
if (href.substr(0, 'http://'.length) == 'http://'){
$(this).attr('href', '/' + href);
}
});
两者都是这样做的。
请注意,它们会为http以外的其他方案生成无效链接(例如/https://example.com/index.html
)。根据您正在使用的HTML代码的清洁程度,您可以只查找冒号以识别绝对链接:
$(function() {
$('a:not([href*=":"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
答案 1 :(得分:0)
首先,您的代码等于以下
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if(true) { $(this).attr('href', '/' + href); }
});
});
如果你真的想根据条件更新href,如果statetment应该不同:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if(href.indexOf('http://') == -1 ) { $(this).attr('href', '/' + href); }
});
});
另一种方式是由@Yogu提供的方式,你很简单,不要为你不会更新的链接循环
答案 2 :(得分:0)
只是Yogu的插件,
请记住,您在每个标签的上下文中。 “在对象本身内部”。 因此,您可以直接访问href。
$('a').each(function() {
if (this.href.substr(0, 'http://'.length) == 'http://'){
this.setAttribute('href', '/' + href);
}
});