我使用 Widget Factory 编写了一个 jquery-ui 小部件...
我需要能够在代码中确定该元素是否已经是一个小部件......
我的 InvestmentGrid 小部件是在 #container 上使用
创建的 $('#container').investmentGrid()
我需要能够确定代码中的其他位置 $('#container') 是否已经是 InvestmentGrid
您可以查询元素的
jQuery.data()
函数,如下所示:
if ($('#container').data('investmentGrid')) {
...
}
您可以尝试使用小部件工厂时为您创建的伪选择器。
$(":namespace-widgetname")
@dan-story 在回答的时候可能已经有了答案,但我发现这个方法不再起作用了。嗯,不完全是。 至少 jQueryUI 1.10 不是这样。根据“实例”部分中http://api.jqueryui.com/jQuery.widget/的文档,您现在需要知道小部件的全名。
例如,如果您使用以下命令创建小部件工厂:
$.widget("Boycs.investmentGrid", ...);
然后,要检查容器是否有它,您可以检查以下内容:
if ($('#container').data('Boycs-investmentGrid'))
{
...
}
仅仅使用名称已经不够了。
@Boycs:根据我的理解,使用 Widget Factory 可以防止您在同一元素上多次实例化插件。 (参考:http://jqueryui.pbworks.com/widget-factory)
此外,如果您想确认“容器”是否已经是一个投资网格,您可以在插件代码中尝试以下选项:
this.element.data("investmentGrid") ===这个;
更多详情可以参考docs.jquery.com/UI_Developer_Guide
当前版本的 jQuery UI(我可以用 1.11.x 来确认)允许您通过
instance()
方法查询小部件的实例。然后它看起来像这样:
$('#container').investmentGrid('instance')
如果元素没有分配
investmentGrid
小部件,您将获得 undefined
。
您也可以使用 call this 来代替:
$(#container').is(':data("namespace-investmentGrid")')
这样做的优点是,即使未加载小部件,它也可以工作。
JQuery UI Widgets 声明如下:
$.widget("rootclassname.investmentGrid", {
options: {
这就是我所做的:
if (typeof ($.rootclassname.investmentGrid) != 'undefined') {
// At this point, we know the investmentGrid.js file has loaded. Now we need to check if the widget has been instantiated.
var widget = document.getElementsByClassName('investmentGrid');
if (!(widget.length && (widget.length > 0))) {
// It has not been instantiated, so do that here. In this case we expect that a DOM element already exists.
var div = document.getElementById('divRootclassnameinvestmentGrid');
if (!div) {
div = document.createElement('div');
div.id = 'divRootclassnameinvestmentGrid';
div.style.display = 'none';
document.body.appendChild(div); // place at end of document.
}
$(div).investmentGrid({});
}
$('.investmentGrid').investmentGrid('somemethodnamecasesensitive');
} else {
alert('Error: The investmentGrid.js widget has not been loaded. Inspect the index.html file to make sure it is specified to load.');
}