如何为jQuery小部件实例创建唯一的id?

Car*_*sen 4 jquery unique widget instance

我正在创建一个基于jQuery小部件的富文本编辑器,它可以在页面上有多个实例.第一个实例应生成如下工具栏:

<input type="checkbox" id="bold-1"><label for="bold-1">..
<input type="checkbox" id="italic-1"><label for="italic-1">..
...
Run Code Online (Sandbox Code Playgroud)

第二个实例应该生成:

<input type="checkbox" id="bold-2"><label for ="bold-2">..
<input type="checkbox" id="italic-2"><label for ="italic-2">..
Run Code Online (Sandbox Code Playgroud)

标签'for'属性需要唯一引用其对应的输入'id'属性.因此,我需要为每个实例添加唯一的ID.

这样的东西可以工作,但我不想在全局命名空间中存储一个计数器:

var textEditorCount;
$.widget("myEditor.textEditor", {
   _create: function () {
      textEditorCount = textEditorCount ? textEditorCount + 1 : 1;
      this.instanceID = textEditorCount;
   },
   ...
};
Run Code Online (Sandbox Code Playgroud)

也许问题归结为:(如何)我可以在窗口小部件的命名空间中存储变量?

Ink*_*bug 6

你可以使用一个闭包:

(function () {
  var textEditorCount;
  $.widget("myEditor.textEditor", {
     _create: function () {
        textEditorCount = textEditorCount ? textEditorCount + 1 : 1;
        this.instanceID = textEditorCount;
     },
     ...
  };
})();
Run Code Online (Sandbox Code Playgroud)

textEditorCount 不再是全球性的了.


Vic*_*tor 5

从 jQuery UI 1.9 开始,每个小部件实例都有唯一的字段this.uuidthis.eventNamespace

this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
Run Code Online (Sandbox Code Playgroud)

https://github.com/jquery/jquery-ui/blob/1.9.0/ui/jquery.ui.widget.js#L215

字段this.eventNamespace适合分配/清除唯一的事件处理程序(http://api.jquery.com/on/ - 阅读“事件名称和命名空间”一章)。