jQuery 如何使用 onclick 事件在同一窗口和选项卡中打开链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16130871/
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 do I open a link in the same window and tab using the onclick event?
提问by MohammadZoghi
I have a page that has multiple divs. I want to get some information from my database to display in some of those divs and I also want it to be displayed as I click on a link to the home div.
我有一个有多个 div 的页面。我想从我的数据库中获取一些信息以显示在其中一些 div 中,并且我还希望在我单击主页 div 的链接时显示它。
I also need the page to be refreshed or reopened in the same window (not in a new page or tab). Last of all, I need the page to be in the home div.
我还需要在同一窗口中刷新或重新打开页面(而不是在新页面或选项卡中)。最后,我需要页面位于主 div 中。
I tried the code below and it didn't work:
我尝试了下面的代码,但没有奏效:
<a href="#home" onclick="window.open('index.jsp#home')" >home</a>
<a href="#home" onclick="location.reload()">home</a>
<a href="#home" onclick="location.href='index.jsp'">home</a>
回答by MohammadZoghi
I used this and it worked
我使用了这个并且它起作用了
<a href="#" class="home_btn" onclick="location.reload();location.href='index.jsp'">???? ????</a>
回答by Rikudo Pain
change your :
改变你的 :
onclick="window.open('index.jsp#home')" >home</a>
to
到
onclick="parent.location='index.jsp#home'">home</a>
no need to reload.
无需重新加载。
回答by Xotic750
like this?
像这样?
<input id="but1" type="button" value="click"></div>
function loadIndex() {
window.location.href = "http://jsfiddle.net/Xotic750/u5nmt/";
}
document.getElementById("but1").addEventListener("click", loadIndex, false);
on jsfiddle
remember jsfiddle is in frames
记住 jsfiddle 在框架中
回答by duckman
The problem with changing location.href
to the current URL with a hash value is that the page won't reload but jump to the given ID.
location.href
使用哈希值更改为当前 URL的问题是页面不会重新加载而是跳转到给定的 ID。
If you really want to jump to the home div then you can just jump with location.href='index.jsp'
and edit your index file
to set location.href = '#home'
on load.
如果您真的想跳转到主 div,那么您可以直接跳转location.href='index.jsp'
并编辑您的索引文件以location.href = '#home'
在加载时进行设置。
If you want to be able to pass information across to the newly loaded page (to provide a specific id) you could use the query string instead, e.g. to jump page use location.href = 'index.jsp?loaddiv=foo
如果您希望能够将信息传递到新加载的页面(以提供特定的 id),您可以改用查询字符串,例如跳转页面使用 location.href = 'index.jsp?loaddiv=foo
Then once the page loads read the query string and use the value to jump to the requested div, e.g.
location.search = '#foo'
然后一旦页面加载读取查询字符串并使用该值跳转到请求的div,例如
location.search = '#foo'
For details on extracting values from the query string see this question.
有关从查询字符串中提取值的详细信息,请参阅此问题。