$(this).attr不起作用

3

我正在使用fancybox,希望在fancybox执行之前获取元素的类。我的代码如下:

$(".agent-file-popup").fancybox({
    'onStart': function () {
        console.log($(this).attr('class'));
        console.log($(".agent-file-popup").attr('class'));
        return true;
    }
});

第一个日志输出 "undefined" 但第二个日志输出了正确的类。为什么在这种情况下我不能使用 "this" 作为元素?

第二个日志在哪里? - gdoron
2
@Andrey,你能正确地定义吗? - gdoron
@Andrey,你知道这可能会改变,就像使用jQuery的$.ajax一样,只要它是按设计和文档正确的。 - gdoron
我修改了问题,应该是 .attr('class') 而不是 .attr('data-paid')。对不起! - user1716672
@Andrey 我已经这样做了,我得到了预期的对象日志。 - user1716672
显示剩余3条评论
2个回答

3

$(this) 是一种常用的构造方式,用于表示当前元素处于焦点状态,可以在事件和选择器函数中使用。这与 JavaScript 的 this 构造方式相同,只不过 jQuery 的函数将其包装以提供对 jQuery 函数的访问。

$(".user").click(function() {
    //Here $(this) will represent the element that was click with class .user
});

插件通常开发作为jQuery的jQuery()函数的扩展,它们很难负责检测当前元素。

因此,当您初始化插件$(this)时,可能很容易表示为空。

Fancybox有一种方法可以获取当前元素。

onstart: function(itemArray, selectedIndex, selectedOpts){
 // selectedIndex holds the current selected box on itemArray as the collection object.
}

0

试试这个:

$(".agent-file-popup").fancybox({
        'onStart' : function() {
           console.log($(this.element).attr('class'));
           console.log($(".agent-file-popup").attr('data-paid'));
            return true;
        }
    });

那又返回了未定义.. - user1716672
如果你在代码中使用 console.log(this),它会返回什么? - Niels
console.log(this) 返回一个 ajax 对象... - user1716672

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接