JQuery .click触发子元素

时间:2012-01-17 23:58:11

标签: jquery

我有一个像这样的倍数div的页面

<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中的链接时,是否有任何建议没有.click触发?

5 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:2)

您可以执行以下操作:

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

这样可以防止.big box divs中的任何标记触发其点击事件。

答案 2 :(得分:1)

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

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

return false应该不会多次打开它,所以试一试,看看它是如何工作的。

答案 3 :(得分: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"));
    }
  })
})

答案 4 :(得分: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();
});
相关问题