Jquery “理解”;这";插件内部

Jquery “理解”;这";插件内部,jquery,plugins,Jquery,Plugins,首先我很抱歉,但我是一个真正的初学者 我不太理解jquery插件中的“this”,我看了很多东西,但找不到任何答案 这是我的插件(我做这个只是为了练习) 电话 $("img").hoverPlugin(); 我的问题是,它会在所有图像上添加动画效果。如果在页面加载的所有图像上设置动画也没关系,但是当我将鼠标放在图像上时,它会设置所有图像的动画 如果我用简单的方式写的话 $("img").animate({"opacity" : ".5"}); $("img").hover(

首先我很抱歉,但我是一个真正的初学者

我不太理解jquery插件中的“this”,我看了很多东西,但找不到任何答案

这是我的插件(我做这个只是为了练习)

电话

$("img").hoverPlugin();
我的问题是,它会在所有图像上添加动画效果。如果在页面加载的所有图像上设置动画也没关系,但是当我将鼠标放在图像上时,它会设置所有图像的动画

如果我用简单的方式写的话

$("img").animate({"opacity" : ".5"});


        $("img").hover(function(){
            $(this).stop().animate({"opacity" : "1"});
        }, function() {
            $(this).stop().animate({"opacity" : ".5"});
        });
这是我想要的方式

因此,如果一个更有经验的开发人员可以向我解释,我如何在我的插件中实现这一点?我会非常高兴的


谢谢

这是因为
中的
这个
。hoverPlugin
函数引用了用于调用它的
$('img')

jQuery.fn.hoverPlugin = function(){
    var element = this;

    $(element).animate({"opacity" : ".5"});

    $(element).hover(function(){
        $(element).stop().animate({"opacity" : "1"});
    }, function() {
        $(element).stop().animate({"opacity" : ".5"});
    });
};
$(document).ready(function(){
    $("img").hoverPlugin();
});

如果您在
console
打开的情况下尝试,您会明白我的意思

如果您只是更改为:

$(element).hover(function(){
    $(this).stop().animate({"opacity" : "1"});
}, function() {
    $(this).stop().animate({"opacity" : ".5"});
});

它起作用了

这样更好:

jQuery.fn.hoverPlugin = function(){
    this
        .animate({"opacity" : ".5"})
        .hover(function(){
            $(this).stop().animate({"opacity" : "1"});
        }, function() {
            $(this).stop().animate({"opacity" : ".5"});
        });
};
您不需要
元素
,只需使用
和链即可

在您的插件上:

var元素=这个;是元素的jquery集合:

并使用它

$("img").hoverPlugin();

非常感谢,谢谢你的帮助,现在我明白了,谢谢你在我的问题上花时间。没问题,很乐意帮忙<代码>:)
jQuery.fn.hoverPlugin = function(){
    var collection = this.animate({"opacity" : ".5"}); //Fade all elements to .5 opactiy.

    collection.each(function() {
        var element = this; // Single element from the collection
            $el = $(element); //Create 1 jquery object and re-use it on the events.

        $el
            .hover(function(){
                $el.stop().animate({"opacity" : "1"});
            }, function() {
                $el.stop().animate({"opacity" : ".5"});
            });
    });

};
jQuery.fn.hoverPlugin = function(){

    var element = this; //this is already wrapped as jquery object e.g it will refer to $("img") in your case

    element.animate({"opacity" : ".5"});


        element.hover(function(){
            element.stop(true,true).animate({"opacity" : "1"});
        }, function() {
            element.stop().animate({"opacity" : ".5"});
        });
};
$("img").hoverPlugin();