如何使用 JavaScript 获取当前 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12391337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the current URL with JavaScript?
提问by Grobi
I would like to get my current URL address, save it to a variable and then pass it to an HTML element:
我想获取我当前的 URL 地址,将其保存到一个变量中,然后将其传递给一个 HTML 元素:
var url = document.URL;
document.getElementById("url").innerHTML = url;
I have tried using document.URL
, window.location
and window.location.href
but none of them works for me. It displays nothing.
我已经尝试使用document.URL
,window.location
并window.location.href
但没有人对我的作品。它什么都不显示。
My HTML is:
我的 HTML 是:
<p id="url"></p>
Thanks in advance!
提前致谢!
Here is my source code:
这是我的源代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
input:hover
{
background: black;
color: white;
border: 0;
}
</style>
<script>
var url = location.href;
document.getElementById("url").innerHTML = url;
function first()
{
var string = "It works!";
write(string);
}
function write(szoveg)
{
alert(szoveg);
}
function submit()
{
var result;
result = confirm("Would you like to confirm your change?");
if(result==true)
window.location="okay.html";
else if(result==false)
alert("You have clicked the \"cancel\" button.");
}
</script>
</head>
<body>
<input type="button" onclick="first()" value="Try Me" />
<p onmouseover="submit()">Hover over this text.</p>
<p id="url">error</p>
</body>
</html>
回答by jfriend00
Now that you have disclosed your entire code, we can see that you are running document.getElementById("url")
too soon before the DOM is loaded. Move your script to the end of the body tag (see fixed code at the end of this answer).
现在您已经公开了整个代码,我们可以看到您document.getElementById("url")
在 DOM 加载之前运行得太快了。将您的脚本移到 body 标签的末尾(请参阅本答案末尾的固定代码)。
Scripts that reference DOM elements cannot be run until those DOM elements are successfully loaded. There are three ways to ensure that.
在成功加载这些 DOM 元素之前,无法运行引用 DOM 元素的脚本。有三种方法可以确保。
The simplest is to just place the script right before the
</body>
tag. Since things in the<body>
tag are loaded sequentially, this ensures that all of your page has been loaded before the script runs and thus the script can reference it.You can code your script to wait for everything in the page to finish loading (including images) by running your code only when the
window.onload
event fires. This waits longer than necessary because it also waits for all images to finish loading, but it is safe and easy.You can code your script to wait until just the DOM is loaded. This is a little tricky to do cross browser since older browsers require different mechanisms. In newer browsers, this time is signified with a
DOMContentLoaded
event on the document.
最简单的方法是将脚本放在
</body>
标签之前。由于<body>
标记中的内容是按顺序加载的,这可确保您的所有页面在脚本运行之前都已加载,因此脚本可以引用它。通过仅在
window.onload
事件触发时运行代码,您可以编写脚本以等待页面中的所有内容(包括图像)完成加载。这等待的时间比必要的要长,因为它还会等待所有图像完成加载,但它既安全又简单。您可以编写脚本以等待仅加载 DOM。这对于跨浏览器来说有点棘手,因为旧浏览器需要不同的机制。在较新的浏览器中,这个时间用
DOMContentLoaded
文档上的事件表示。
window.location.href
contains the current page URL. This always works and is the correct way to obtain the URL of the current page.
window.location.href
包含当前页面 URL。这始终有效,并且是获取当前页面 URL 的正确方法。
Working demo: http://jsfiddle.net/jfriend00/yGrxU/
工作演示:http: //jsfiddle.net/jfriend00/yGrxU/
If this doesn't work in your page, then you have something else wrong in your code. It could be because you are running your code too early before the DOM is loaded and thus document.getElementById()
isn't working. You can fix that by moving your javascript code to the end of the body tag.
如果这在您的页面中不起作用,那么您的代码中还有其他错误。这可能是因为您在 DOM 加载之前过早地运行了代码,因此document.getElementById()
无法正常工作。您可以通过将您的 javascript 代码移动到 body 标签的末尾来解决这个问题。
Another possibility is that you have a script error in your page that is stopping execution of your javscript. You should check the browser error console or the debug console to see if there are any script errors being reported.
另一种可能性是您的页面中存在脚本错误,导致您的 javscript 停止执行。您应该检查浏览器错误控制台或调试控制台以查看是否报告了任何脚本错误。
Now that you've posted your entire code, we can see that you need to move the script to right before the </body>
tag like this:
现在您已经发布了整个代码,我们可以看到您需要将脚本移动到</body>
标签之前,如下所示:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
input:hover
{
background: black;
color: white;
border: 0;
}
</style>
</head>
<body>
<input type="button" onclick="first()" value="Try Me" />
<p onmouseover="submit()">Hover over this text.</p>
<p id="url">error</p>
<script>
var url = location.href;
document.getElementById("url").innerHTML = url;
function first()
{
var string = "It works!";
write(string);
}
function write(szoveg)
{
alert(szoveg);
}
function submit()
{
var result;
result = confirm("Would you like to confirm your change?");
if(result==true)
window.location="okay.html";
else if(result==false)
alert("You have clicked the \"cancel\" button.");
}
</script>
</body>
</html>
回答by Alessandro Minoccheri
Try this , you can botain the url of your page and put it into a variable
试试这个,你可以获取页面的 url 并将其放入一个变量中
window.location.href
回答by Paul
Your problem is that these two lines:
你的问题是这两行:
var url = location.href;
document.getElementById("url").innerHTML = url;
Execute before your <p>
tag exists. Remove them from your script and add a new script after your p
tag:
在您的<p>
标签存在之前执行。从您的脚本中删除它们并在您的p
标签后添加一个新脚本:
<p id="url"></p>
<script>
var url = location.href;
document.getElementById("url").innerHTML = url;
</script>
See this JSFiddle
看到这个JSFiddle
It might be even nicer to use a script that replaces itself with a text node containing the url. Then you don't need to give the p
an id
if you don't use that id anywhere else:
使用用包含 url 的文本节点替换自身的脚本可能会更好。然后p
,id
如果您不在其他任何地方使用该 ID ,则无需提供an :
<p>
<script>
(function(){
var scripts = document.getElementsByTagName('script');
var this_script = scripts[scripts.length - 1];
this_script.parentNode.replaceChild(
document.createTextNode(location.href),
this_script
);
})();
</script>
</p>
See this JSFiddle
看到这个JSFiddle