jQuery:在对象文字中使用$(this)

时间:2016-01-13 20:33:30

标签: jquery

假设我们有这段代码:

$.fn.obList   = function(options){
  alert(options.o1);
}

$('li').obList({
  o1: $(this).attr('class')
});

我试图在给予函数的选项对象中访问所选元素(即 li ), 但是$(this)不起作用并返回 undefined

2 个答案:

答案 0 :(得分:2)

下面:

$('li').obList({
  o1: $(this)
});

this的上下文是window。所以你需要使用:

$('li').each(function () {
  $(this).obList({
    o1: $(this)
  });
});

您也可以使用:

$.fn.obList   = function(options) {
  alert($(this).attr("class"));  // This `this` here refers to the element.
};

输出:http://output.jsbin.com/qekonadomu



$.fn.obList   = function(options){
  alert(options.o1);
};

$('li').each(function () {
  $(this).obList({
    o1: $(this).attr("class")
  });
});

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<ol>
  <li class="item-1"></li>
  <li class="item-2"></li>
  <li class="item-3"></li>
</ol>
&#13;
&#13;
&#13;

为此,我得到:

item-1
item-2
item-3

作为输出。

答案 1 :(得分:0)

您必须创建一个范围,其中this是元素,并且可以通过多种方式完成,常见的方法是使用each()

$('li').each(function() {
    $(this).obList({
        o1: $(this).attr('class')
    });
});

另一种方法是让插件处理它

$.fn.obList   = function(options){

    return this.each(function() {
        options = options || {};

        options.o1 = $(this).attr('class');
    });
}

$('li').obList();
相关问题