【发布时间】:2015-12-15 05:43:45
【问题描述】:
我的 HTML 代码如下:
<a href="#" onclick="reloadPage()">Text</a>
当用户在链接上单击“鼠标左键”时,应该调用 reloadPage()。
但是当用户在链接上使用“Ctrl + 单击”或“中间按钮”单击时,我想打开一个不使用 reloadPage() 的新窗口。
我该怎么做?
【问题讨论】:
标签: javascript html hyperlink tabs
我的 HTML 代码如下:
<a href="#" onclick="reloadPage()">Text</a>
当用户在链接上单击“鼠标左键”时,应该调用 reloadPage()。
但是当用户在链接上使用“Ctrl + 单击”或“中间按钮”单击时,我想打开一个不使用 reloadPage() 的新窗口。
我该怎么做?
【问题讨论】:
标签: javascript html hyperlink tabs
您可以参考here。这是我的代码
<a href="#" id="test" onclick="reloadPage(event)">Click Me</a>
<script>
$(document).ready(function() {
$(document).keydown(function(event){
if(event.which==17)
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
});
var cntrlIsPressed = false;
function reloadPage(mouseButton,event)
{
//event.preventDefault();
if( event.which == 2 ) {
//todo something
//window.open($("#test").attr("href"));
alert("middle button");
return false;
}
if(cntrlIsPressed)
{
//window.open($("#test").attr("href"));
// ctrl + click
return false;
}
//todo something
window.location.href = $("#test").attr("href");
return true;
}
</script>
【讨论】:
您可以简单地将a标签上的href属性设置为当前页面的url,这样当用户点击它会打开同一个页面(重新加载),如果他中间点击它会打开同一个页面在新标签中。
如果你想在多个页面上使用它,那么你可以将 javascript 中的 href 设置为当前页面的 url,如下所示
document.getElementById('myId').href = location.href
【讨论】:
window.history打开页面后检查页面是否在新选项卡中打开
你可以试试这个方法(html):
<a href="#" id="mylink">Text</a>
Javascript:
$(function () {
$("#mylink").click(function (event) {
if ((event.button == 0 && event.ctrlKey) || event.button == 1) {
event.preventDefault();
window.open("http://www.google.com");
}
else
if (event.button == 0)
window.location.reload();
});
});
【讨论】:
我有两种选择。纯 javascript 和使用 jquery。
这是完整的代码。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#jqueryStyle').mousedown(function(e){
//3 is right click
if(e.which == 3){
window.open("http://www.w3schools.com");
//1 is for click
}else if(e.which == 1){
reloadPage();
}
});
});
function reloadPage(){
location.reload();
}
function onMouseDown(e,obj){
e = e || window.event;
//3 is for right click
if(e.which == 3){
window.open("http://www.w3schools.com");
//1 is for click
}else if(e.which == 1){
reloadPage();
}
}
</script>
</head>
<body>
<a href="#" id="jqueryStyle">JQuery Code</a ><br/>
<a href="#" onmousedown="onMouseDown(event,this)">Pure Javascript Code</a >
</body>
</html>
希望对您有所帮助。
【讨论】: