2012-01-17 73 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")); 
    } 
    }) 
})