开发者

jquery change onclick event of href

开发者 https://www.devze.com 2023-01-20 04:21 出处:网络
I have a href element and that has onclick event on it. I want to change the function after some event. I tried using jquery but the old one and new function both are fired. I want only the new one t

I have a href element and that has onclick event on it. I want to change the function after some event. I tried using jquery but the old one and new function both are fired. I want only the new one t be fired.

My Code is as:

<a href='#' id='cvtest' onclick='tes开发者_StackOverflow社区tMe("One")' >TEST</a>
 after some event i am adding following code:
$("#cvtest").click(function(){ testMe("Two"); });  

When i click "Test" link i get 2 alerts "One" and "Two".

How to stop the first event getting fired or is there any other solution to this problem?


Don't use the deprecated onclick property. Assign both event handlers using jQuery. Then it's easy to remove the one you no longer want.

// Add the original event handler:
var originalEventHandler = function() { 
    testMe('One');
};
$("#cvtest").click(originalEventHandler);

// Then later remove it and add a new one:
var newEventHandler = function() { 
    testMe('Two');
};
$("#cvtest").unbind('click', originalEventHandler).click(newEventHandler);
0

精彩评论

暂无评论...
验证码 换一张
取 消