JavaScript/JQuery : use $(this) in a variable-name

标签 javascript jquery internet-explorer this default-value

我正在编写一个 jquery-plugin,它会根据某些用户操作更改某些元素的 css 值。 在其他操作中,css-value 应重置为其初始值。

因为我找不到恢复初始 css 值的方法,所以我只是创建了一个数组,在开头存储所有初始值。

我这样做是为了:

var initialCSSValue = new Array()

在我的插件开始时,后来,在某种设置循环中,我使用了我所有的元素都可以访问

initialCSSValue[$(this)] = parseInt($(this).css('<CSS-attribute>'));

这在 Firefox 中工作得很好。 但是,我刚刚发现,IE(甚至 v8)在使用

再次访问特定值时遇到问题
initialCSSValue[$(this)]

代码中的其他地方。我认为这是因为我使用对象 ($(this)) 作为变量名。

有办法解决这个问题吗?

谢谢

最佳答案

使用 $(this).data()

起初我打算建议使用 ID 和属性名称的组合,但每个对象可能都没有 ID。相反,使用 jQuery 数据函数将信息直接附加到元素,以便轻松、独特地访问。

做这样的事情(其中 <CSS-attribute> 替换为 css 属性名称):

$(this).data('initial-<CSS-attribute>', parseInt( $(this).css('<CSS-attribute>') ) );

然后你可以像这样再次访问它:

$(this).data('initial-<CSS-attribute>');

使用 data 的替代方法:

在你的插件中,如果你想避免太多的话,你可以像这样做一个小的辅助函数data用法:

var saveCSS = function (el, css_attribute ) {
   var data = $(el).data('initial-css');
   if(!data) data = {};
   data[css_attribute] = $(el).css(css_attribute);
   $(el).data('initial-css', data);
}
var readCSS = function (el, css_attribute) {
   var data = $(el).data('initial-css');
   if(data && data[css_attribute])
     return data[css_attribute];
   else
     return "";
}

关于JavaScript/JQuery : use $(this) in a variable-name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223524/

相关文章:

javascript - 清除 MIDI 输出缓冲区

javascript - 图片拖放、上传——只允许上传一张图片?

javascript - 我怎样才能找出是什么脚本将我的元素的可见性设置为隐藏?

javascript - 为什么这个网站会导致IE撕裂?

javascript - Adobe InDesign Javascript 错误!错误号 : 55 Error String: Object does not support the property or method 'documentPreferences'

javascript - 匿名函数包装局部变量并返回新函数

html - Internet Explorer 不在 VS 2013 上加载 css。Chrome 会

css - 如何在IE9中使用Order?

javascript - 可以在外部 JS 文件上加载传单吗?

jquery - 响应式幻灯片过渡看起来很奇怪