jQuery,在输入 [type=radio] 更改时验证某些内容,如果为假,则调用其他 2 个函数

jQuery, on input[type=radio] change verify something if false, call 2 other functions

我正在尝试创建一个事件,根据 input[type=radio]id 触发一些函数。如果单击的 Id 与 maybe_evtDiag 不同,则应调用 this.applySubConditionalRequired();this.bindUISubActions();。为什么我的代码不起作用?

var SubFormStuff = {

  init: function()
    this.applySubConditionalRequired();
    this.bindUISubActions();
  },

  bindUISubActions: function() {
    // when a radio or checkbox changes value, click or otherwise
    $("input[type='radio'].stepThreeDiag").change(function() {
      if($(this).attr("id") == "maybe_evtDiag") {
        $(this).prop('checked', false);
      }else{

       //this is not working //
        applySubConditionalRequired(this);
        displaySubFormRequired(this);

      }
    });
  },

  applySubConditionalRequired: function() {
    $(".require-if-subevent-active").each(function() {
      var el = $(this);
      // does something
    });
  },

  displaySubFormRequired: function() {
    $(".div-subevent-class").each(function() {
      var el = $(this);
      // does something else
    });
  }

};

SubFormStuff.init();

就像您在 init() 中所做的那样,添加对对象 (this) 的引用以调用同级函数(不丢失上下文):

bindUISubActions: function() {
  var _SubFormStuff = this;
  // when a radio or checkbox changes value, click or otherwise
  $("input[type='radio'].stepThreeDiag").change(function() {
    if($(this).attr("id") == "maybe_evtDiag") {
      $(this).prop('checked', false);
    } else{    
      _SubFormStuff.applySubConditionalRequired();
      _SubFormStuff.displaySubFormRequired();
    }
  });

有关 scope and context in JavaScript

的更多详细信息

你应该这样调用方法:

bindUISubActions: function() {

    // Store the reference to the current object
    var self = this;

    // when a radio or checkbox changes value, click or otherwise
    $("input[type='radio'].stepThreeDiag").change(function() {
        if($(this).attr("id") == "maybe_evtDiag") {
            $(this).prop('checked', false);
        } else{
            self.applySubConditionalRequired();
            self.displaySubFormRequired();
        }
    });
 }

通过这种方式,您可以将 self 当前作用域赋给 self,并稍后在同一执行作用域中的任何其他函数调用中使用它。

More about javascript scope

你试图在错误的上下文中调用 applySubConditionalRequired(this)displaySubFormRequired(this) 你应该得到 applySubConditionalRequired 和 displaySubFormRequired 是未定义。

试试这个:

bindUISubActions: function() {
   // when a radio or checkbox changes value, click or otherwise
   var that = this;
   $("input[type='radio'].stepThreeDiag").change(function() {
       if($(this).attr("id") == "maybe_evtDiag") {
       $(this).prop('checked', false);
       }else{

       //it should work now //
       that.applySubConditionalRequired(this);
       that.displaySubFormRequired(this);

      }
  });
},