gpt4 book ai didi

javascript - 在 .on() 或任何对象文字中创建可重用变量

转载 作者:行者123 更新时间:2023-11-29 22:19:11 25 4
gpt4 key购买 nike

有时我遇到这样的情况,我必须创建相同的变量,并在对象内部一遍又一遍检索完全相同类型的信息文字,例如 .on() 出于纯粹的好奇心,以及必须有更好的方法这一事实,我来了。

注意不是在谈论 jQuery .data() 或任何类型的普通 window. global多变的。我说的是在对象文字的闭包中维护的一个。

当然,其中一些变量实时变化,因此我总是将它们放在 .on() 的每个方法中

恰当的例子:

$(document).on({
focusin: function () {
var placeHolder = $(this).attr('data-title'),
status = $(this).attr('data-status');
// etc etc
},
focusout: function () {
var placeHolder = $(this).attr('data-title'),
status = $(this).attr('data-status');
// etc etc
},
mouseenter: function () {
// same variables
},
mouseleave: function () { }
}, '.selector');

有没有办法将变量存储在某处,并在每个事件上检索?它们需要是动态的

$(document).on({
// Basially:

// var placeHolder; etc
// each event gets these values

focusin: function () {
// now here I can simply use them
if (placeHolder === 'blahblah') {}
// etc
}
}, '.selector');

最佳答案

您可以使用 event data将一些静态变量传递给事件,以及通过方法技巧来传递“动态”变量:

$(document).on({
focusin: function(e) {
var attrs = e.data.getAttributes($(this)),
var1 = e.data.var1;

var placeHolder = attrs.title,
status = attrs.status;
// ...
},
focusout: function(e) {
var attrs = e.data.getAttributes($(this)),
var1 = e.data.var1;

var placeHolder = attrs.title,
status = attrs.status;
// ...
},
// ...
}, ".selector", {
// static variables
var1: "some static value",

// dynamic "variables"
getAttributes: function($this) {
return {
title: $this.data("title"),
status: $this.data("status")
};
}
});

演示: http://jsfiddle.net/LHPLJ/

关于javascript - 在 .on() 或任何对象文字中创建可重用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13385317/

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