Returning variable from function is undefined once returned
Is there any reason that this:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
console.log(daddy,"result");
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
})
});
would return a jQuery object in the console (expected behaviour), where as the following returns Undefined
All I am doi开发者_如何学Pythonng is moving the call to console.log
outside the function, and after the call to it:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
console.log(next,"result");
})
});
You're missing the return
statement in your else
condition. If your function recurses, then the top level call won't return anything, and you'll end up with undefined
.
else {
return find_parent_p(daddy);
}
I'm not sure if this is causing the problem, but the function only works if it finds the element immediately.
- Make
daddy
a local variable (to prevent possible conflicts with global variables) - Return the result from the recursive call
:
function find_parent_p(x) {
var daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p') {
return daddy;
} else {
return find_parent_p(daddy);
}
}
Note: You can do the same using just jQuery:
var next = $(this).closest('p');
If you aim to get the img's parent which is p, you can use.
$('img').each(function(){
next = $(this).closest('p');
console.log(next,"result");
})
精彩评论