2011-08-14 55 views

回答

61

讓你的回調回報false並傳遞到onclick處理程序:

<a href="#" onclick="return callmymethod(24)">Call</a> 

function callmymethod(myVal){ 
    //doing custom things with myVal 
    //here I want to prevent default 
    return false; 
} 

要創建維護代碼但是,您應該放棄使用「嵌入式Javascript」(即:直接位於元素標記內的代碼)並通過包含的元素修改元素的行爲Javascript源文件(它被稱爲unobtrusive Javascript)。

的加價:

<a href="#" id="myAnchor">Call</a> 

代碼(單獨的文件):

// Code example using Prototype JS API 
$('myAnchor').observe('click', function(event) { 
    Event.stop(event); // suppress default click behavior, cancel the event 
    /* your onclick code goes here */ 
}); 
+0

http://jsfiddle.net/aamir/Tcs3w/不工作 –

+1

@AamirAfridi是的,它工作。你應該調整你的小提琴,並將'onLoaded'改爲'no wrap'。或者直接編寫自己的.html標記。 –

+0

請參閱下面的答案! 「在我看來,答案是錯誤的!他要求提供event.preventDefault();當你簡單地返回false時,它調用event.preventDefault();以及event.stopPropagation();」! –

27

嘗試

<a href="#" onclick="callmymethod(24); return false;">Call</a> 
+0

好簡直是最好的。我想要這個\t event.preventDefault(); –

16

在我看來,答案是錯的!當你簡單地返回false時,他要求event.preventDefault();;它也叫event.preventDefault();event.stopPropagation();

您可以通過此解決它:

<a href="#" onclick="callmymethod(event, 24)">Call</a> 

function callmymethod(event, myVal){ 
    //doing custom things with myVal 

    //here I want to prevent default 
    event.preventDefault(); 
} 
+4

你依賴於'window.event',這在瀏覽器中並不總是可用的。 –

2

只需將 「的javascript:無效(0)」,在href標記

<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a> 
0

地方的 「#」 給一個class和id到元素並使用jquery函數unbind();

$(".slide_prevent").click(function(){ 
       $(".slide_prevent").unbind(); 
       }); 
5

您可以捕獲該事件,然後用preventDefault()方法阻止它 - 工程與純JavaScript

document.getElementById("xyz").addEventListener('click', function(event){ 
    event.preventDefault(); 
    console.log(this.getAttribute("href")); 
    /* Do some other things*/ 
}); 
+0

這是正確的答案。謝謝 –

6

這爲我工作

<a href="javascript:;" onclick="callmymethod(24); return false;">Call</a> 
+1

這是唯一的工作!謝啦! –

+0

不用擔心,很高興聽到它:) – Pixelomo