Bos*_*nBB 1 javascript url jquery href
这个脚本:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if ("a:not(http://)") {
$(this).attr('href', '/' + href);
}
});
});
Run Code Online (Sandbox Code Playgroud)
将斜杠添加到每个链接甚至包含"http://"的链接不知道为什么?我没有收到任何错误?
关于如何解决这个问题的任何想法?
你混淆了两件事:
jQuery选择器:
$(function() {
$('a:not([href^="http://"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
Run Code Online (Sandbox Code Playgroud)和纯javascript if语句:
$('a').each(function() {
var href = $(this).attr('href');
if (href.substr(0, 'http://'.length) == 'http://'){
$(this).attr('href', '/' + href);
}
});
Run Code Online (Sandbox Code Playgroud)两者都是一样的.
请注意,它们将为除http(例如/https://example.com/index.html)之外的其他方案生成无效链接.根据您正在使用的HTML代码的清洁程度,您可以只查找冒号以识别绝对链接:
$(function() {
$('a:not([href*=":"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
Run Code Online (Sandbox Code Playgroud)