jquery 删除 .change() 处理程序

问题描述 投票:0回答:2

我一直在尝试找出如何删除

.change()
jquery 处理程序,但没有运气。当选择单选按钮时,我使用它来激活某些表单字段,但我不希望它为每个后续更改触发。

$('.radio').change(function(){
    alert("changed");
    $('.fields').removeAttr('disabled');
    //this is where I try removing the change handler
    $(this).off('change');
});


JSfiddle 演示

jquery html forms
2个回答
10
投票

您的代码仅从已更改的单选按钮中删除处理程序,而不是从组中删除

改变

// 'this' only removing the handler from the radio button that was changed
$(this).off('change');

// removing the handler of all radio button
$('.radio').off('change');

你的代码

$('.radio').change(function(){
  alert("changed");
  $('.fields').removeAttr('disabled');
  $('.radio').off('change');
});

http://jsfiddle.net/q5jqqgnt/3/


3
投票

您的代码实际上有效,但唯一的问题是您仅针对您单击的单选按钮关闭“更改”事件。尝试使用

$(".radio").off('change');
而不是
$(this).off('change');

© www.soinside.com 2019 - 2024. All rights reserved.