2012-10-18 36 views
2

消防Click事件可能重複:
Can I call jquery click() to follow an <a> link if I haven’t bound an event handler to it with bind or click already?在A-標籤

我寫了下面的代碼。

<div style="background-color:orange">Click me to open the link 
    <br> 
    <a target="_blank" href="http://example.com">Link</a> 
</div> 

<script> 
    jQuery('div').click(function(){ 
     jQuery('a').click(); 
    }); 

    jQuery('a').click(function(e){ 
     alert('It came here!');   
     e.stopPropagation(); 
     return true; 
    }); 
</script> 

但鏈接未打開。

UPDATE:將目標屬性添加到A標籤。

+0

看到它在行動http://jsfiddle.net/zZqQs/ –

+1

檢查此http://jsfiddle.net/ZeSdV/5/其工作正常.. – Codegiant

+0

@SandipSarkar它是什麼? –

回答

1

首先,您使用的選擇器將與您網頁上的所有<a>標籤匹配。也許你想給你的<a> id屬性,讓你可以針對一個特定的元素...

<a href="foobar.html" id="foo">foo</a> 

您也可以嘗試使用trigger功能模擬元件上的點擊 -

$('#foo').trigger('click'); 

最後要提的一件事是,您實際上沒有調用該方法來打開鏈接。您可以嘗試使用此代碼 -

jQuery('a').click(function(e){ 
    alert('It came here!'); 
    window.open($(this).attr('href'));  
    return false; 
}); 

參考 -

說明:執行附加爲 匹配元素的所有處理程序和行爲給定的事件類型。

+0

Lix,爲了簡化問題,我使用標籤本身作爲選擇器。 –

+0

@hab - 好的......它看起來有點奇怪:) – Lix

+1

jQuery文檔說'.click()'等價於'.trigger(「click」)''。 – Barmar

1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>  
<div style="background-color:orange">Click me to open the link 
    <br> 
    <a href="http://example.com" target="_blank">Link</a> 
</div> 

<script> 
    $('div').click(function() { 
     $('a').click(); 
    }); 

    $('a').click(function (e) { 

     alert('It came here!'); 
     e.stopPropagation(); 
     window.location = $("a").attr("href"); 
     return true; 
    }); 
</script> 
+0

我想將'target ='_ blank''添加到A標籤。它會在那個時間工作嗎? –

3
<div style="background-color:orange">Click me to open the link 
    <br> 
    <a id="b" href="http://example.com">Link</a> 
</div> 

jQuery('div').click(function(){ 
    document.getElementById('b').click(); 
}); 

小提琴:http://jsfiddle.net/zZqQs/4/

OR:

jQuery('a')[0].click(); 

看來,jQuery的點擊和原材料JS點擊互不相同。

+0

如果你已經在使用jQuery函數,那麼使用vanilla JavaScript的原因是什麼? – Lix

+0

@Lix查看答案編輯 – karaxuna