亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

jQuery自執行功能不觸發

jQuery自執行功能不觸發

九州編程 2022-06-16 16:43:04
我正在將我的意大利面條 jQuery 代碼重構為組件。到目前為止,我已經構建了一個組件,它被封裝在一個自激發函數中。$(document).ready(function () {    debugger;});(function () {    Component.init();    var Component = {        init: function () {            this.cacheDom();            this.bindEvents();            debugger;        },        cacheDom: function () {            //Initialize properties        },        bindEvents: function () {            //setup eventhandlers        },        function1: function (event) {            //do some work here        },    };})();我的 jQuery 正在訪問 dom.ready 函數,但我的自動執行函數沒有做任何事情。另外,我確實嘗試刪除自執行函數并初始化我的組件,$(document).ready(function)但它沒有達到debugger我放在 init 函數中的那個..我已經多次查看我的代碼,似乎無法弄清楚為什么Component根本沒有初始化。
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

您可以通過更新當前的模塊模式來解決此問題,例如:


// This is our main Component module

//---------------------------------------------------

var Component = (function() {


  // All private variables here

  //---------------------------------------------------

  var $blog;


  // Place initialization logic here

  //---------------------------------------------------

  var init = function() {

    console.log('Inside init()')

    cacheDom();

    bindEvents();

  };

  

  // Cache all required DOM elements here

  //---------------------------------------------------

  var cacheDom = function() {

    //Initialize properties

    console.log('Inside cacheDom()')

    $blog = $('#blog');

  };

  

  // All event handler setup here

  //---------------------------------------------------

  var bindEvents = function() {

    //setup eventhandlers

    console.log('Inside bindEvents()')

    $blog.on('click', function1);  

  };

  

  // All other methods here

  //---------------------------------------------------

  var function1 = function(event) {

    //do some work here

  };


  // Return the methods you want to make public

  //---------------------------------------------------

  return {

    init,

  };

})();


$(document).ready(function() {

  console.log('Inside document.ready()')

  Component.init();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


使用此模塊,我們確保Component.init()僅在 DOM 完全準備好時才調用它。關于這種模式的一個更有趣的事情是,我們現在只能init()從外部訪問公共方法,而所有其他私有方法,如cacheDom(),bindEvents()都不能從外部訪問。從而Component.cacheDom();將返回undefined。我認為除了init()您不需要公開任何其他方法,因為您的所有邏輯現在都將在Component模塊內處理。


查看完整回答
反對 回復 2022-06-16
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號