开发者

Possible JQuery class selector bug

I have an ajax call that returns a HTML fragment. I am trying to select a div in that fragment before rendering.

An example of the HTML:

<div class="event-detail repBy-container">
    <div class="copy">.....</div>
    <div class="links">
       ....
    </div>
    <div class="contacts">
      <div class="name-brand">....</div><div class="details">...., <a href="mailto:...@..开发者_高级运维..">...</a></div>
    </div>
</div>

Now the problem:

function ajaxReturn(data) {
   alert($(data).find('.event-detail').length); <-- Returns 0
   alert($(data).find('.copy').length); <-- Returns 1
}

Is this a bug or am I doing something wrong?


.find() gets descendants only, not from the current level, you'd need .filter() to get items from the current set (which is the root of what you returned), like this:

function ajaxReturn(data) {
   alert($(data).filter('.event-detail').length); //<-- Returns 1
   alert($(data).find('.copy').length); //<-- Returns 1
}

If you want .find() to work in both cases, add the content to a parent container, like this:

function ajaxReturn(data) {
   var parent = $("<div />").append(data);
   alert(parent.filter('.event-detail').length); //<-- Returns 1
   alert(parent.find('.copy').length); //<-- Returns 1
}


This is the expected behavior.

  • You are searching for .event-detail under your div and there isn't any.
  • You are searching for .copy under your div and there is one.


It depends on what is being passed into the ajaxReturn function. ie what does data contain?

If it contains the HTML you quoted then this is expected behaviour. This is because the .find() method searches within the current context, not including it. If the outer div in your example is the outer div in data then .find() will be searching for .event-detail inside of that div.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜