Need to know if a jQuery UI Widget has been applied to a DOM object

后端 未结 5 1896
我寻月下人不归
我寻月下人不归 2021-02-18 12:52

I\'m using jQuery and have some interactions with a jQuery UI where I need to get options. However there\'s a possibility that the jQuery UI function has not been applied yet t

相关标签:
5条回答
  • 2021-02-18 13:10

    According to this discussion, the recommended way to detect if a widget has been rendered on an element is as follows:

    var hasWidget = $('selector').is(':ui-widgetname');
    
    0 讨论(0)
  • 2021-02-18 13:11

    As of jQuery UI 1.11, widgets can be directly tested for via the instance method:

    var hasProgressbar = ($(element).progressbar("instance") !== undefined);
    

    Documentation: http://api.jqueryui.com/jQuery.widget/#method-instance

    0 讨论(0)
  • 2021-02-18 13:23

    You can access the progress bar object on the element by doing:

    $("#myid").data("progressbar")
    

    So to use this:

    var progressBar = $("#myid").data("progressbar");
    if ( progressBar == null ) {
        // handle case when no progressbar is setup for my selector
    } else {
        alert("The value is: " + progressBar.value());
    }
    
    0 讨论(0)
  • 2021-02-18 13:26

    I prefer to use hasOwnProperty on any object in JavaScript, since it returns a boolean every time.

    var hasWidget = $( "selector-here" ).data().hasOwnProperty( "widget-name-here" );
    if ( hasWidget )
    {
        // Put your awesome code here.
    }
    

    Which IMHO is a little better than checking null; what if it switches to undefined, which, also IMO is what it should return.

    0 讨论(0)
  • 2021-02-18 13:34

    The DOM object will get an extra CSS class appended to it: "ui-progressbar". If you View Source on http://docs.jquery.com/UI/Progressbar then you can see a div with id=progressbar and nothing more, but if you use Firebug and click the element you can see it has a few more classed added.

    Edited: I think that @jamiebarrow's solution is the more correct one here.

    0 讨论(0)
提交回复
热议问题