Difference between find and filter in jquery

谁说我不能喝 提交于 2019-11-26 22:53:15

问题


I'm working on fetching data from wiki pages. I'm using a combination of php and jquery to do this. First I am using curl in php to fetch page contents and echoing the content. The filename is content.php:

$url = $_GET['url'];
$url = trim($url," ");
$url = urldecode($url);
$url = str_replace(" ","%20",$url);

echo "<a class='urlmax'>".$_GET['title']."</a>";
echo crawl($url);

Then jQuery is used to find the matched elements.

$.get("content.php",{url:"http://en.wikipedia.org/w/index.php?action=render&title="+str_replace(" ","_",data[x]),title:str_replace(" ","_",data[x])},function(hdata){
                        var imgs = $(hdata).find('a.image img');
                        var ent = $(hdata).filter('a.urlmax');


                        ent = $(ent[0]).text();


});

I was able to successfully get images but for the variable ent when I use find instead of filter, it's returning an empty array. Only filter is working. Why is this?

Edit: I know the basic difference between find and filter. Here both the a.image img and a.urlmax are descendats of the hdata. Then why find does not work on a.urlmax. Not a.urlmax alone it's not working on any other class or id


回答1:


.find() http://api.jquery.com/find/

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Filter, on the other hand, works on the currently matched elements. That's why filter worked but find did not (you needed to look at the current element).




回答2:


filter will select subset of element from the selected element

find will select descendent/children of selected element

To make it more clear filter will search through all element whereas find will search only in the descendent list




回答3:


.find()

It will returns descendant elements of the selected element.

Exemple (jsfiddle):

    <style>
      .Cell{
         margin: 15px;
         width: 400px;
         border: 2px solid lightgrey;

      }
      .Cell * {
         display: block;
         border: 2px solid lightgrey;
         color: lightgrey;
         padding: 5px;
         margin: 10px;
    }
    </style>

    <div class='Cell Plus'>div (1)
      <div class='Plus'>Child</div>
    </div>

    <div class='Cell Plus'>div (2)
      <div class='Plus'>Child</div>
    </div>

JS:

$(".Cell").find(".Plus").css({"color": "red", "border": "2px solid red"});

Result:


.filter()

It will returns elements that match a certain criteria.

Using the same html above:

$(".Cell").filter(".Plus").css({"color": "red", "border": "2px solid red"});

Result:



来源:https://stackoverflow.com/questions/10378757/difference-between-find-and-filter-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!