jQuery:在对象文本中使用$(this)
假设我们有以下代码:jQuery:在对象文本中使用$(this),jquery,Jquery,假设我们有以下代码: $.fn.obList = function(options){ alert(options.o1); } $('li').obList({ o1: $(this).attr('class') }); 我试图访问给定给函数的选项对象中的选定元素(即li), 但是$(this)不起作用,返回未定义。您必须创建一个作用域,其中this是元素,这可以通过多种方式完成,一种常见的方法是使用each() 另一种方法是让插件处理它 $.fn.obList = fun
$.fn.obList = function(options){
alert(options.o1);
}
$('li').obList({
o1: $(this).attr('class')
});
我试图访问给定给函数的选项对象中的选定元素(即li),
但是
$(this)
不起作用,返回未定义。您必须创建一个作用域,其中this
是元素,这可以通过多种方式完成,一种常见的方法是使用each()
另一种方法是让插件处理它
$.fn.obList = function(options){
return this.each(function() {
options = options || {};
options.o1 = $(this).attr('class');
});
}
$('li').obList();
在这里:
此
的上下文是窗口
。因此,您需要使用:
$('li').each(function () {
$(this).obList({
o1: $(this)
});
});
您还可以使用:
$.fn.obList = function(options) {
alert($(this).attr("class")); // This `this` here refers to the element.
};
输出:
$.fn.obList=函数(选项){
警报(选项1);
};
$('li')。每个(函数(){
美元(本)。债务人({
o1:$(this.attr(“类”)
});
});代码>
您确定第二种解决方案吗。我不能让它工作。这个
指向窗口还是单个元素?@alex-每个循环都不是为了得到类,它通常是需要的,而且总是一个好的实践,在jQuery插件中->作为旁注,在jQuery原型方法中,此
已引用jq matched set对象,它应该始终返回它以保持链接(除非用作getter)@a.Wolff Sure bro<代码>:)
$('li').each(function () {
$(this).obList({
o1: $(this)
});
});
$.fn.obList = function(options) {
alert($(this).attr("class")); // This `this` here refers to the element.
};