开发者_StackOverflowi'm trying to write my own autosuggest plugin, using jquery tutorial, wich should work with dynamically created fields. But i have no success. For example:
(function( $ ){
$.fn.dataSuggester = function(options) {
//By using $.extend we merge predefined options with passed in plugin
var options = $.extend({location:false, minlength:3, category:false}, options);
var stop_keys = [16, 17, 18, 19, 20, 33, 34, 35, 36, 37, 38, 39, 40, 44, 45, 46, 91, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144];
return this.each(function() {
var o = $(this);
var suggestWrapper = $('<div class = "data-suggester suggest-box-wrapper">');
o.focus(function() {
console.log('aaaaa');
});
...............................
});
};
})( jQuery );
When i try to use it like
<script type = "text/javascript">
$('.dataSuggest').dataSuggester();
</script>
It works perfect for all elements except dynamically created :(
Of course i can call my plugin in other way, like
<script type = "text/javascript">
$('.dataSuggest').live('focus', function() {$(this).dataSuggester();});
</script>
, but i think it is not as pretty as i want.
When i try to make something like this:
o.live('focus', function() {console.log('aaaa');});
It doesn't work. Please, help me anyone?
.live
is an event binding function. It works by taking the description of the wrapped set .dataSuggest
and binding the specified event whenever a new element matching that description is found.
A jQuery plugin works by executing a function on an already selected set of elements. These are two totally different activities.
If you want your plugin to use .live
then it needs to, at some point, have the description of target elements being passed in (as opposed to a wrapped set of the target elements themselves).
Consider something like this:
// Plugin in use:
$.dataSuggest({ targetElements: '.customClass' });
// Plugin code:
$.fn.dataSuggester = function(options) {
$(options.targetElements).live('focus', function(e) {
// your code here...
});
};
Note how the plugin isn't being used on a wrapped set $('.whatever').dataSuggest()
, but instead being executed as a plain function on the jQuery object.
精彩评论