4

我有以下代码:

<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 函数,将持有者(我需要获取)作为参数传递。

这是 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 );
        },
    }
})
4

2 回答 2

7

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 );
        },
    }
})
于 2012-01-23T01:52:26.940 回答
0

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

于 2012-01-23T02:31:04.987 回答