调用 jQuery 插件时获取 DOM (选择器)元素
Get DOM (selector) element when calling jQuery plugin
我如何从插件调用本身访问插件被调用的实际元素? $(this)
似乎指的是插件上下文而不是实际元素。
例如,我在输入字段上调用 pluginName 插件,我想要一个回调来更改该输入的值。这是一个通用的例子。元素可以是标签、class、id 等
$('element').pluginName({
option: true,
option: false,
onSelect: function(item){
$(this).val('something');
//console.log($(this));
}
});
this
在 onSelect
事件中的上下文将取决于库的结构方式以及对该事件处理程序的内部调用方式。理想的解决方案是将 onSelect
处理程序的范围设置为元素本身,或者至少将其作为参数提供给处理程序。
如果那不可能,并且您想保留对 #input
元素的引用,您可以再次 select 它,因为应该只有一个元素实例 id
:
onSelect: function(item){
$('#input').val('something');
}
如果您使用 class 到 select 多个元素,那么您需要遍历它们:
$('.input').each(function() {
var $el = $(this);
$el.pluginName({
option: true,
option: false,
onSelect: function(item) {
$el.val('something');
}
});
});
如果你的插件不允许,没有直接的方法。你可以做的一件事是
var $el = $('#input');
$el.pluginName({
option: true,
option: false,
onSelect: function(item){
$el.val('something');
}
});
我如何从插件调用本身访问插件被调用的实际元素? $(this)
似乎指的是插件上下文而不是实际元素。
例如,我在输入字段上调用 pluginName 插件,我想要一个回调来更改该输入的值。这是一个通用的例子。元素可以是标签、class、id 等
$('element').pluginName({
option: true,
option: false,
onSelect: function(item){
$(this).val('something');
//console.log($(this));
}
});
this
在 onSelect
事件中的上下文将取决于库的结构方式以及对该事件处理程序的内部调用方式。理想的解决方案是将 onSelect
处理程序的范围设置为元素本身,或者至少将其作为参数提供给处理程序。
如果那不可能,并且您想保留对 #input
元素的引用,您可以再次 select 它,因为应该只有一个元素实例 id
:
onSelect: function(item){
$('#input').val('something');
}
如果您使用 class 到 select 多个元素,那么您需要遍历它们:
$('.input').each(function() {
var $el = $(this);
$el.pluginName({
option: true,
option: false,
onSelect: function(item) {
$el.val('something');
}
});
});
如果你的插件不允许,没有直接的方法。你可以做的一件事是
var $el = $('#input');
$el.pluginName({
option: true,
option: false,
onSelect: function(item){
$el.val('something');
}
});