从小部件内部获取保存jquery小部件的div对象

时间:2012-01-23 01:43:24

标签: jquery jquery-ui widget jquery-widgets

我有以下代码:

<div id="widHolder"></div>
<script type="text/javascript" language="javascript">
    $('#widHolder').widgetName({
        optionOne: false,
        optionTwo: 1,
        onComplete: function (holder) { 
            // ... do something here with the 'widHolder' object such as $(holder).addClass(x,y) 
        }
    });
</script>

在窗口小部件本身中,将在窗口小部件完全初始化后立即调用onComplete方法。我希望窗口小部件中的代码引用窗口小部件链接到的对象(在本例中,id为'widHolder'的div)。

我的目标是通过创建上面列出的oncomplete函数,快速轻松地引用保持对象。小部件本身的代码只是调用onComplete函数传递holder(我需要获取)作为参数。

以下是jQuery UI Widget插件的代码示例

(function ($) {
    $.widget("ui.widgetName", {
        options: {
            // ... other options that can be set
            onComplete: undefined
        },

        // called on the initialization of the widget
        _init: function () {
            // do initialization functions...

            if(this.options.onComplete)
                this.options.onComplete( I_WANT_TO_SEND_THE_DOM_ELEMENT_HERE );
        },
    }
})

2 个答案:

答案 0 :(得分:6)

jQuery UI Widget Factory通过以下方式使元素可用:

来自插件的

this.element

有关详细信息,请查看此处:http://wiki.jqueryui.com/w/page/12138135/Widget%20factory

这样可以更好地回答您的问题吗?

(function ($) {
    $.widget("ui.widgetName", {
        options: {
            // ... other options that can be set
            onComplete: undefined
        },

        // called on the initialization of the widget
        _init: function () {
            // do initialization functions...

            if(this.options.onComplete)
                this.options.onComplete( this.element );
        },
    }
})

附注 - 如果您在插件中创建了另一个闭包,则需要保存对this的引用。例如:

(function ($) {
    $.widget("ui.widgetName", {
        options: {
            // ... other options that can be set
            onComplete: undefined
        },

        // called on the initialization of the widget
        _init: function () {
            // do initialization functions...
            var self = this;
            $.each(an_array_or_something_obj, function(){
                //here this will refer to the current element of the an_array_or_something_obj
                //self will refer to the jQuery UI widget
            });
            if(this.options.onComplete)
                this.options.onComplete( this.element );
        },
    }
})

答案 1 :(得分:0)

如果在您的示例中,持有人是小部件的直接父级,请使用this.offsetParent