简体   繁体   English

这两个 jQuery 代码片段有什么区别?

[英]What is the Difference Between These two jQuery Code Snippets?

I'm rather new to jQuery and I came across something.我对 jQuery 很陌生,我遇到了一些事情。 What is the difference between these code snippets?这些代码片段有什么区别? I think they'll do exactly the same thing.我认为他们会做同样的事情。

 $("p.expendable").on('mouseover', function(){ $(this).remove(); }); $('p').on('mouseover', function() { $('p.expendable').remove(); });

They are different.他们是不同的。

Considering the first case , if the current hovered p element have expendable class then it will remove that specific element.考虑第一种情况,如果当前悬停的p元素具有expendable类,那么它将删除该特定元素。

 $("p.expendable").on('mouseover', function() { $(this).remove(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="expendable"> Testing</p> <p> Testing 2</p> <p> Testing 3</p>

In second case the currently hovered element is any p tag irrespective of whether it have any class or not, then it will remove all p element which have 'expendable' class在第二种情况下,当前悬停的元素是任何p标签,无论它是否有任何类,然后它将删除所有具有“消耗性”类的p元素

 $('p').on('mouseover', function() { $('p.expendable').remove(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="expendable"> Testing</p> <p> Testing 2</p> <p> Testing 3</p>

delegate is cleaner:代表更干净:

$(document).delegate("p.expendable", 'mouseover', function(){
   $(this).remove();
});

It says, if p.expendable is created, attach function to it that deletes itself.它说,如果创建了p.expendable ,则将删除自身的函数附加到它。 (deprecated!) Good catch on this one @ epascarello (已弃用!)很好地抓住了这个@ epascarello

Use:利用:

$(document).on("p.expendable", 'mouseover', function(){
       $(this).remove();
    });

or just:要不就:

$("p.expendable").on('mouseover', function(){
           $(this).remove();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM