作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个基于 jQuery 小部件的富文本编辑器,它可以在页面上有多个实例。第一个实例应该生成一个像这样的工具栏:
<input type="checkbox" id="bold-1"><label for="bold-1">..
<input type="checkbox" id="italic-1"><label for="italic-1">..
...
第二个实例应该生成:
<input type="checkbox" id="bold-2"><label for ="bold-2">..
<input type="checkbox" id="italic-2"><label for ="italic-2">..
标签“for”属性需要唯一引用其相应的输入“id”属性。因此我需要为每个实例添加一个唯一的 id。
这样的东西可以工作,但我不喜欢在全局命名空间中存储计数器:
var textEditorCount;
$.widget("myEditor.textEditor", {
_create: function () {
textEditorCount = textEditorCount ? textEditorCount + 1 : 1;
this.instanceID = textEditorCount;
},
...
};
也许问题可以归结为:(如何)我可以在小部件的命名空间中存储变量吗?
最佳答案
您可以使用闭包:
(function () {
var textEditorCount;
$.widget("myEditor.textEditor", {
_create: function () {
textEditorCount = textEditorCount ? textEditorCount + 1 : 1;
this.instanceID = textEditorCount;
},
...
};
})();
textEditorCount
将不再是全局的。
关于jquery - 如何为 jQuery 小部件实例创建唯一的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11504583/
我是一名优秀的程序员,十分优秀!