gpt4 book ai didi

javascript - 未分配闭包变量

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

我有以下内容:

jQuery.fn.X = function(){
var elements = jQuery(this);
elements.click(function(){
var self = jQuery(this);
//elements here is not defined why?
});

为什么 elements 没有在 on click 函数中定义,而它应该将其作为闭包变量?

最佳答案

这是创建 jQuery 插件的正确方法。

jQuery.fn.X = function () {
// here, "this" will be a jQuery object containing all elements you matched
// with X(). You must return that object.
return this.click(function () {
// here, "this" will be a DOM element. You don't have to return it.
var self = jQuery(this);
// ...
});
});

您必须返回 jQuery 才能保持方法链接正常工作。

关于javascript - 未分配闭包变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17387487/

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