2013-02-14 87 views
3

我有幾個鏈接,在發送響應之前需要幾秒鐘來處理,所以我想實現一個指示器圖標。這裏是我的起點:從鏈接中刪除「可點擊性」(錨點標記)

<a href="/foo"><img src="icon.png" /></a> 

這是一個傳統的應用程序,並且代碼已經是一個爛攤子,所以我不介意和使用內聯事件處理程序:

<a href="/foo"><img src="icon.png" onclick="indicate(this)" /></a> 

而且,世界上沒有JS框架綁定在一起。我可以使用其他一些機制來應用事件處理程序,但這不會改變我試圖解決的問題。

由於後端處理消耗大量資源,我想讓用戶不要多次點擊。我試圖在第一次點擊時刪除href屬性。看起來,通過使用超時發送請求後,href被正確刪除,但firefox和IE9都允許我再次單擊該鏈接。

這裏的指示()函數:

function indicate(e) { 
    if (indicator.ref.nodeName) indicateStop(); 

    // save state 
    indicator.ref = e; 
    indicator.orig.href = indicator.ref.parentNode.href; 
    indicator.orig.src = indicator.ref.src; 

    // replace icon 
    indicator.ref.src = indicator.src; 

    // remove href 
    setTimeout(function(){ indicator.ref.parentNode.removeAttribute("href"); }, 20); 
} 

所以,問題是,我怎麼能點擊它刪除一個鏈接(錨)的「可點擊」?

+0

您是否嘗試在點擊事件處理程序中返回false?我應該這樣做。 – ldionmarcil 2013-02-14 17:41:10

+1

禁用默認事件['event.preventDefault'](https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault)並自己處理它(您也應該將光標外觀更改爲'默認「,當你禁用鏈接)。 – steveax 2013-02-14 17:44:12

+0

@steveax這是否意味着我也必須自己處理錨點目標查找? - 另外,光標已經變回,並且當我第二次單擊時,href不再被設置。 – codecab 2013-02-14 17:50:11

回答

0

有了這個代碼,您可以從打開的鏈接錨停止:

$('a').on('click', function(e){ 
    e.preventDefault(); 
}); 
+0

,看起來非常像jquery。 OP似乎在使用香草。 – Popnoodles 2013-02-14 17:45:37

+0

你正確的修復它看起來更好:P – 2013-02-14 17:49:06

+0

它仍然看起來非常像jQuery! – Popnoodles 2013-02-14 17:50:13

-1
<a id="indicate" href="/foo"><img src="icon.png" /></a> 

document.getElementById('indicate').addEventListener('click', indicate, false); 

function indicate(e) { 
    e.preventDefault(); 
} 

有人會說使用返回false,有時不錯,但不是最好的主意。 event.preventDefault() vs. return false

+0

在我的情況下,e實際上是我點擊的元素..所以沒有e.preventDefault() – codecab 2013-02-14 17:56:20

+0

哦,也許不是... – Popnoodles 2013-02-14 18:06:57

+0

...現在它確實 – Popnoodles 2013-02-14 18:15:05