【问题标题】:Custom event not fired when called from $(document).ready();从 $(document).ready() 调用时未触发自定义事件;
【发布时间】:2015-02-12 13:55:08
【问题描述】:

我有以下代码

$(document).ready(function () {

    VerifyCustomerFilter();

    $("#ToDateStor").on("DateSet", function () {
       ...
    );

   function VerifyCustomerFilter() {
     if(toDate != "")     
       $("#ToDateStor").trigger('DateSet'); //This does not work
   }
}

当我在函数 'VerifyCustomerFilter ()' 中的条件为真时,无法触发我创建的自定义事件。

但是当我在 DatePicker 的事件中触发事件时,它可以完美运行:请参阅

 $("#calTo").datepicker({
      showButtonPanel: false,
      onClose: function (dateText, inst) {
          var ToDate = $(this).val().toString();
          $('#ToDateStor').html(ToDate).trigger('DateSet'); // This works!
      }
 });

也已经尝试过使用triggerHandler()

我应该做错什么?

【问题讨论】:

  • 你在绑定监听器之前触发事件
  • @atmd 你应该回答这个问题。

标签: jquery custom-events jquery-trigger jquery-triggerhandler


【解决方案1】:

您在将侦听器绑定到元素之前触发您的事件,请尝试

$(document).ready(function () {
    // add the listener
    $("#ToDateStor").on("DateSet", function () {
       ...
    });

    // define the function
    function VerifyCustomerFilter() {
        if(toDate != "")     
            $("#ToDateStor").trigger('DateSet'); //This does not work
        }
     }

     // call the function
     VerifyCustomerFilter();
});

【讨论】:

  • 是的,我最终混合了事物的顺序,现在它工作正常。谢谢你的时间!
【解决方案2】:
$(document).ready(function () {

 function VerifyCustomerFilter() {
     if(toDate != "")     
       $("#ToDateStor").trigger('DateSet'); //This should work now
   }


    $("#ToDateStor").on("DateSet", function () {
       ...
    );
  //First bind the event,then call it
    VerifyCustomerFilter();

}

你在绑定事件之前调用了函数。

【讨论】:

  • trigger() 不绑定事件,.on() 绑定,所以请检查你的答案
  • @empiric 这很尴尬。谢谢你指出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多