简体   繁体   English

HTML:当有人单击我的网站上的链接时,浏览器会打开2个选项卡?

[英]HTML: Browser opens 2 tabs when someone clicks a link on my web site?

I have the following HTML code: 我有以下HTML代码:

<div onclick="window.open('http://example.com')" >
<p>1234 Main St, New York, NY</p>
<p>Price: $200,000/p>
<p>4 Beds / 3 Baths</p>
<p>2000 sqft</p>
<a href="http://example.com">More Info</a>
</div>

If the person hovers over the part of the DIV that is not the hyperlink, it only opens one window. 如果此人将鼠标悬停在DIV的非超链接部分上,则只会打开一个窗口。

If the person clicks on the hyperlink within the DIV, it opens 2 windows (one for the DIV and one for the hyperlink). 如果该人单击DIV中的超链接,则会打开2个窗口(一个用于DIV,一个用于超链接)。

Is there any way around this 2x opening window scenario? 有什么办法可以解决这种2倍打开窗口的情况?

简单的解决方案:

<a href="http://example.com" onclick="return false;">More Info</a>

You could make the div clickable by making the link into a block element with css 您可以通过使用CSS使链接成为一个块元素来使div可点击

div a {
    display: block;
}

I came across the same issue and please don`t laugh on my silly mistake. 我遇到了同一问题,请不要为我的愚蠢错误大笑。 But two tabs was opening because i am having a link and having target='_blank' and also calling a function too on the same like: 但是两个选项卡正在打开,因为我有一个链接,并具有target ='_ blank',并且也在相同的地方调用了一个函数,例如:

<pre>
$('#foo').on('click',function(){
// some code
window.open("https://www.google.com","_blank");
});

where also i have added the target as _blank. 我也在哪里将目标添加为_blank。 i removed the target attribute from the anchor and it works fine for me. 我从锚中删除了目标属性,它对我来说很好。 Hope you are not doing same. 希望你做的不一样。

That's because the click event bubbles up. 这是因为click事件冒泡了。 It initiates when you click the anchor element, than bubbles up to the div, and executes that too. 当您单击锚元素时,它会启动,然后气泡到div并执行。

You need to capture the click event inside the div (using a function), and then call the event's stopPropagation method to stop it from bubbling up. 您需要捕获div内部的click事件(使用函数),然后调用该事件的stopPropagation方法以阻止它冒泡。

More info about event bubbling here: http://www.quirksmode.org/js/events_order.html 有关事件冒泡的更多信息, 请参见http : //www.quirksmode.org/js/events_order.html

You could use the same function in both the DIV and the A HREF, and manage the opening inside that function to call the window only once, that will work. 您可以在DIV和A HREF中使用相同的函数,并管理该函数内部的打开以仅调用一次窗口,这将起作用。

Edit : If you care at least a little about Search Engine Optimization you should not use that caption for the link, but more something mentionning the content of the next page like "House details" or better depending of the context/look of the page. 编辑:如果您至少关心搜索引擎优化,则不应为链接使用该标题,而应根据页面的上下文/外观,更多地提及下一页的内容,例如“房屋详细信息”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM