gpt4 book ai didi

jquery - 如何制作一个像 fadeIn 这样不将元素作为参数的函数

转载 作者:行者123 更新时间:2023-12-01 04:37:34 25 4
gpt4 key购买 nike

嘿伙计们,我想做一个像这样的函数:fadeIn()fadeIn() 函数不接受任何参数,但它会自动知道我正在谈论的元素。例子:我如何知道如何创建一个函数:

function make100HW(el){
$(el).animate({height:"100px",width:"100px"},400);
}

make100HW("#something");

//what I want is something like
// $("#something").make100HW(); without putting the element inside the parameters.
//just like $("#something").fadeIn();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="something" style="background:red">
</div>

最佳答案

要制作 jQuery 插件,您需要将函数添加到 jQuery.fn 对象(通常也可以通过 $.fn 获得,但是一个编写良好的插件不应该假设 $ 指的是 jQuery)。在函数中,this 将是调用插件的 jQuery 集(不是单个 DOM 元素,因为它在事件处理程序回调等中)。

通常,插件会足够复杂,需要辅助功能。出于这个原因,并且因为您不应该依赖 $,所以通常会看到封装在 IIFE 中的插件代码接受 $ 作为参数并传入 jQuery :

(function($) {
// Code using $ here, which is fine even though noConflict
// may have been used in the global context...
})(jQuery);

所以:

// Your plugin code
(function($) {
$.fn.make100HW = function make100HW() {
// 1. Use `this`, which is hte current jQuery set
// 2. Return `this`, for chaining (which animate does)
return this.animate({height:"100px",width:"100px"},400);
};
})(jQuery);

// Using it
$("#something").make100HW();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="something" style="background:red">
</div>

关于jquery - 如何制作一个像 fadeIn 这样不将元素作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413082/

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