设置完成后,在HTML中获取BASE,但不使用页面URL

问题描述 投票:9回答:6

在构建HTML页面时,在php中动态设置基础:

$base_line = '<base href="' . $some_path . '/" /> ';
echo $base_line;

现在,我在HTML页面中,我需要访问此信息($ some_path),搜索几个小时后,我似乎找不到答案。请注意,加载的HTML页面有一个与基础无关的URL,我无法访问PHP代码来修改它。加载的页面可以有一个类似于:http://xyz.com/index.php的URL,但页面中的所有其他链接将基于基础设置的值,因此我无法使用页面URL获取基础。

我想我可以像图像一样抓取其中一个元素并使用DOM解剖它以找到基础,但应该有一种更简单的方法来做到这一点。有任何想法吗?

使用window.location在这种情况下不起作用,因为它将返回与加载的页面URL相关的内容,而不是在其中设置为基础的内容。

javascript html base
6个回答
26
投票

如果要获取基本元素的值,可以执行以下操作:

var baseHref = document.getElementsByTagName('base')[0].href

或者更安全一点:

var bases = document.getElementsByTagName('base');
var baseHref = null;

if (bases.length > 0) {
    baseHref = bases[0].href;
}

更新:更简洁的方式是:

const baseHref = (document.getElementsByTagName('base')[0] || {}).href;

如果它没有baseHref<base>可能为null。


更新2:使用getElementsByTagName()而不是使用querySelector()

var base = (document.querySelector('base') || {}).href;
console.log(base);
<base href="http://www.google.com"/>

6
投票

不需要jquery,jqlite或过时的API。使用更新的querySelector API:

var base = document.querySelector('base');
var baseUrl = base && base.href || '';

3
投票

我遇到的一个问题是使用element.href并不能完全返回所设置的内容。例如,如果你有这个:

<base href="/some/sub/directory/" />

那么element.href会给你:

document.getElementsByTagName('base')[0].href
# http://example.com/some/sub/directory/

我发现你可以通过使用jQuery attr函数来避免这种情况:

$("base").attr("href")
# /some/sub/directory/

如果你想避免使用jQuery,你也可以使用getAttribute函数:

document.getElementsByTagName('base')[0].getAttribute("href")
# /some/sub/directory/

0
投票

每个节点都有一个只读属性baseURI,它返回绝对基本URL,如果无法获取绝对URI,则返回null。

要获取文档的基本URL,您可以使用:document.baseURI

如果您只想要路径名或URL的任何其他部分,则可以创建URL对象:

var baseLocation = new URL(document.baseURI);
var pathname = baseLocation.pathname;

-1
投票

如果您无法访问PHP,可以尝试使用javascript window.location.hostname

如果你想要的东西

http://www.example.com/blahblah/blah.html

比这三件事情更有效

window.location.protocol = "http"
window.location.host = "example.com"
window.location.pathname = "blahblah/blah.html"

var url = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;

你可以看看这个article的基本网址功能


-1
投票

如果您使用的是jqLit​​e(angularjs默认值),则代码如下所示:

base = angular.element(document.querySelector('base')).attr('href')

有关详细信息,请参阅angular document

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.