我运行了一些代码JavaScript(jQuery)代码来监听<a href="">
次点击,并将其替换为数据属性中的链接。
<a class="js-external" href="http://www.google.com/" data-href="/tracking.php?url=http://www.google.com/">Google</a>
<script type="text/javascript">
$('a.js-external').click(function(e) {
var hrefNew = $(this).attr('data-href');
if (hrefNew) {
e.preventDefault();
window.location.href = hrefNew;
}
});
</script>
这可以按预期工作,但会破坏某些浏览器行为。如果用户ctrl
+ click
在链接上(要在新窗口中打开),则网址仍会在同一窗口中打开。
我怎么能不打破常规浏览器?我是否还应该检测用户是否按住ctrl
然后使用window.open()
?
答案 0 :(得分:0)
这是因为您正在阻止默认操作
e.preventDefault();
正如您在问题中提到的那样,您必须跟踪按下控制键并在新窗口中打开。
if(e.ctrlKey)
window.open(hrefNew)
else
window.location.href = hrefNew;
但如果您不希望这样做,那么最简单的方法是动态设置锚点的href
属性。
$('a.js-external').click(function(e) {
var hrefNew = $(this).attr('data-href');
if (hrefNew) {
$(this).attr("href",hrefNew);
}
});