Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery:在对象文本中使用$(this)_Jquery - Fatal编程技术网

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.
    };