jQuery selector context not working within $().find
My question is about "this" (selector context) within the jQuery $().find function.
My code below grabs a collection of li
.
Then uses that collection to "find" an h3.
Then adds a div element a开发者_C百科fter the h3 and attempts to use the $().data function to associate the new div element onto the h3 for later use.
Does anyone know why when I run this code the $(this) inside of the data function returns the DOCUMENT and not an li
from the $posts collection?
var $posts = $('#blog ul').children();
$posts.find("h3").after("<div></div>").data("div", $(this).parent().find('div'))
yes, you are implying that calling the function find()
somehow creates a scope. The this context can only be created within a function:
function(){
this // now means the context of this function which might be window
}
if it is the case that there will only be 1 h3 in the posts collection you could cache it.
Otherwise you are looking for the each
method;
var $posts = $('#blog ul').children();
$posts.find('h3').each(function(){
var $this = $(this);
$this.after('<div/>').data('div', $this.parent().find('div'));
});
精彩评论