2012-01-17 67 views
3

我有一个用倍数div的页面这样JQuery的。点击上的子元素触发

<div class="bigbox"> 
    <a href="http://www.somestuff.com">some stuff</a> 
    more elements 
</div> 

我试图让每个DIV打开里面的链接点击,并试图像当:

$('div.bigbox').each(function(){ 
    $(this).click(function(){ 
     window.open($(this).find('a').attr("href")); 
})}) 

但是当点击实际链接时,它会打开它两次。任何建议没有。点击触发点击我的div内的链接?

回答

1

我相信你和你的代码非常接近。试试这个:

$('div.bigbox').click(function() 
{ 
    window.open($(this).find('a').attr('href')); 
    return false; 
}); 

return false应该保持它打开不止一次,所以给一个尝试,看看它是如何工作的。

+0

第一次尝试这种之一,它确实工作。 我只尝试在'a'元素中添加'return false'来尝试在启用javascript时阻止它,但是这完全阻止了链接。 – Charles 2012-01-18 13:50:57

2

通过打开两次,我假设你的意思是在原始窗口和新窗口中都遵循链接。

只需添加return falsee.preventDefault()即可停止此操作。

$('div.bigbox').click(function(e){ 
    e.preventDefault() 
    window.open($(this).find('a').attr("href")); 
}); 
2

你可以这样做:

$('div.bigbox').find('a').click(function(e) { 
    e.preventDefault(); 
}); 

这将防止任何标签iniside烧制而成的单击事件.bigbox的div。

0

在我看来,你会更好,只是这样做:

<a href="http://www.somestuff.com"> 
    <div class="bigbox"> 
     More elements 
    </div> 
</a> 

如果你宁愿使用JavaScript,你总是可以只是这样做:

$('div.bigbox').click(function(e) 
{ 
    window.open($(this).find('a').attr('href')); 
    e.preventDefault(); 
}); 
1

你想你处理程序被调用时div被点击,但不是当div内的链接被调用?

如何添加

$('div.bigbox').each(function(event){ 
    $(this).click(function(){ 

    // only perform the action if the div itself was clicked 
    if (event.target == this) { 
     window.open($(this).find('a').attr("href")); 
    } 
    }) 
})