我有这样的插件构造:
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html);
});
}
};
var button = {
html: '<button class="btn">Button</button>'
};
var input = {
html: '<input type="text" class="input" value="" />'
};
var actions ={
clicked:function(){
alert('clicked');
},
hover:function(){
alert('hover');
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
点击添加按钮,您将添加input.html
的输入和button.html
的按钮。如何为actions.clicked
中的输入元素和按钮对象初始化click事件,并从actions.hover
悬停事件
答案 0 :(得分:0)
您可以在追加按钮和输入时定义事件。请尝试以下代码,我希望这有用。
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html)
.find(".foo")
.click(function(){actions.clicked($(this))})
.hover(function(){actions.hover($(this))})
});
}
};
var button = {
html: '<button class="btn foo">Button</button>'
};
var input = {
html: '<input type="text" class="input foo" value="" />'
};
var actions ={
clicked:function($this){
console.log($this);
},
hover:function($this){
console.log($this);
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;