我正在编写一个简单的 jQuery 插件,将输入标签转换为时间格式的元素(在模糊时它将 245p 更改为下午 2:45)。
由于我不想将时间格式事件应用到同一个元素两次,我需要一种方法来检测提供的列表中的特定元素是否尚未应用格式。
这是代码的相关部分:
var methods = {
init : function(sel) {
var $this = $(sel);
return $this.each(function(){
var data = $(this).data('time_formatted');
if (data) {
return;
} else {
$(this).data('time_formatted', true);
我听说在插件中使用 $(sel).data()
不是一个好主意;相反,请使用 $.data()
。我不知道为什么,这就是我听到的;老实说,我不知道有什么区别。
所以我的问题是,这是完成检查特定元素是否已在插件中应用时间格式化程序的方法吗?
如果您想查看当前开发状态下的插件,请参阅 http://jsfiddle.net/userdude/xhXCR/ .
谢谢!
贾里德
最佳答案
你在哪里听说过使用.data()
不好? jQuery's plugin autoring页面说:
Often times in plugin development, you may need to maintain state or check if your plugin has already been initialized on a given element. Using jQuery's
data
method is a great way to keep track of variables on a per element basis. However, rather than keeping track of a bunch of separate data calls with different names, it's best to use a single object literal to house all of your variables, and access that object by a single data namespace.
所以应该没问题。
关于javascript - 在 jQuery 中使用 $.data() 在元素上存储标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723900/