jquery改变href的onclick事件

发布于 2024-09-27 07:39:21 字数 372 浏览 1 评论 0原文

我有一个 href 元素,上面有 onclick 事件。我想在某些事件发生后更改功能。我尝试使用 jquery 但旧函数和新函数都被触发。我只想解雇新人。

我的代码如下:

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

当我单击“测试”链接时,我收到 2 个警报“一”和“二”。

如何阻止第一个事件被触发或者是否有其他解决方案来解决这个问题?

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='testMe("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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

老子叫无熙 2024-10-04 07:39:21

不要使用已弃用的 onclick 属性。使用 jQuery 分配两个事件处理程序。然后就可以轻松删除您不再需要的那个了。

// 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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文