jQuery new UI problem
$.widget("ui.myWidget", {
_init: function() {
//start
alert('Hello World!!!');
}
}
I have the above widget/ui
when i call it like so...
<div onclick="$('#id').myWidget()">
Click Me
</div>
i get the "Hello World!!!" alert box. if i click it again then nothing happens.
i don't know if im missing something... bu开发者_如何学运维t i need the ui to alert each time its i click the div.
note: this is a short code to simplify and make it easy to understand....
You're calling the widget in the wrong way. You want your element to "become" your widget, so you'd set your widget element like you would any other jQuery UI widget, ie. $('element').scrollable()
, .draggable()
, etc.
Inside your widget delcaration, you want to set all the listeners and events to each element that the widget is set to. So if you want something to fire on click of your widget element, you would set a click event to this.element
, referring to the current widget element, in this case your div.
The _init
function is only called once, like everyone else has said, as it initializes your widget. However, if you set it up correctly, the click event should fire on every click of your element. This should help.
HTML:
<div id="hello_world">Click Me</div>
JS:
$.widget("ui.myWidget", {
_init: function() {
//start
this._show();
var thisWidget = this;
this.options.handler.click(function(){
thisWidget._show();
});
},
_show: function(){
alert('Hello World???');
}
});
$('div#click_me').click(function(){
$('#id').myWidget({handler: $(this)});
});
__init is only run once. Make another function to do whatever you actually need to do. There's a good primer here
So in the head add the widget as you are now but with an extra function to do the dirty work and then change the onclick to something along the lines of $('#id').myWidget.myAlertFunction()
精彩评论