gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:56:00 26 4
gpt4 key购买 nike

我正在创建一个基于 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/

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