Jquery plugins jQuery插件、作用域和将创建的元素绑定到';改变';事件
所以,我正在写我的第一个插件。我正在使用,因此我的插件设置如下所示:Jquery plugins jQuery插件、作用域和将创建的元素绑定到';改变';事件,jquery-plugins,scope,jquery,Jquery Plugins,Scope,Jquery,所以,我正在写我的第一个插件。我正在使用,因此我的插件设置如下所示: (function( $ ){ var methods = { init : function( options ) { var $this = $(this); // do some code. // Add an element $this.append('<select id="test"><option value="yes">Ye
(function( $ ){
var methods = {
init : function( options ) {
var $this = $(this);
// do some code.
// Add an element
$this.append('<select id="test"><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler (chose '.on' after reading the documentation for '.delegate')
$this.on('change', '#test', methods['handler'].call($this, $('#test').val()));
},
handler : function( content ) {
alert ('You chose: ' + content);
}
};
$.fn.testbed = function( method ) {
// Method calling logic
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 + ' does not exist' );
}
};
})( jQuery );
对于函数调用,它是有效的
但是,我现在调用函数的方式不起作用。这是我从其他方法中调用其他函数的方式,但它不适用于处理程序
所以,我的问题是:(1)如何让它调用函数?(2)这是设置处理程序的最佳位置吗?id在页面中应该是唯一的。拥有多个具有相同id的元素将使您获得一个不同于您在尝试访问它时所想的元素。完全不要使用id,在回调中使用
this
,以获取正确的元素
为每个事件创建委托时,没有理由创建委托。直接绑定select元素上的事件
事件的处理程序应该是函数,而不是函数调用的结果
init : function( options ) {
// Add an element
this.append('<select><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler
$('select', this).on('change', function() {
methods['handler']($(this).val());
});
},
init:函数(选项){
//添加一个元素
this.append('Yes'+
"否";;
//绑定更改处理程序
$('select',this).on('change',function()){
方法['handler']($(this.val());
});
},
但是,我现在调用函数的方式不起作用。
…这是怎么回事?上面代码中的这一行:$This.on('change','#test',methods['handler')。call($This,$('#test').val())代码>耶,我知道id的正确用法,我只是为了这个例子才这样做的。在真实版本中,我使用的是一个类。我试试这条路,谢谢!这是可行的,但我想知道如果“handler”函数中的select框没有作为参数传递,如何获取它的值“这”似乎是jQuery对象。@coding_hero:如果希望处理程序在元素的作用域中运行(this
是DOM元素)而不向其发送任何参数,可以使用$('select',this.)。on('change',methods['handler'])代码>来绑定它。
init : function( options ) {
// Add an element
this.append('<select><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler
$('select', this).on('change', function() {
methods['handler']($(this).val());
});
},