gpt4 book ai didi

javascript - 超越在 document.ready() 中编写简单函数

转载 作者:行者123 更新时间:2023-11-30 00:11:26 25 4
gpt4 key购买 nike

<分区>

在构建站点时,作为个人喜好,我喜欢创建一个主 javascript 文件,该文件的顶部有 window.load 和 window.ready。

作为易读性的一种方式,我倾向于将这些函数中我想要的任何逻辑重构到它们自己的函数中,通常我只在元素存在于 DOM 中时运行这些函数。

在大多数情况下,我觉得这比将所有内容直接转储到加载/就绪函数中更干净,但是随着我的 javascript 技能的提高,我开始编写更多的匿名函数,我的代码开始看起来有点像随着文档就绪部分开始变长而变得困惑。

为了这个问题的目的,我想知道:

  1. 有没有更好的方法来只运行一个函数/代码来像我一样检查长度?
  2. 有没有更好的方法将上述检查合并到我编写插件的方式中?
  3. 主要问题:我如何超越编写单一的以 jQuery 为中心的脚本,作为提高我的 javascript 技能的一种方式。

我已经提供了我的文件的外观示例。

$(window).load(function() {
if ( $('#el-1').length !== 0 ) { $('#el-1').addClass('add'); }
});

$(document).ready(function() {
if ( $('#el-2').length !== 0 ) { new my_plugin('#el-2'); }
if ( $('#el-3').length !== 0 ) { simple_function(); }
/* This starts to get messy when there's multiple checks,
// longer function names, and different libraries etc.
*/
});

var simple_function = function() {
//do the short thing
};

;(function( window, $ ) {
'use strict';
function my_plugin( el, options ) {
this.el = $(el);
this.options = $.extend( this.defaults, options );
this._init();
}
my_plugin.prototype = {
defaults : {
something: 'something'
},
_init : function() {
// do the things
}
_internalFunction: function() {
// do the things
},
externalFunction: function() {
// do the things
}
}
window.my_plugin = my_plugin;
})( window , jQuery );

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com