jQuery - using length to find div after ajax call
UPDATE:
The issue was the div was in a div that was hidden, when divs are hidden length, offset(), position() don't work properly.
// Original Post below.
This should be simple.I'm trying to test if a div exsists on the page after an ajax .html() output
if($('#'+mydiv).开发者_运维知识库length != 1) { // do stuff }
there is only one problem, if the div your searching for is not there when (document).ready fires then .length doesn't see it.
You could just use the size() method
if($('#'+mydiv).size() != 1) {
// do stuff
}
This recounts the number of matching elements in the DOM.
If you are performing an async request, which I assume you are (async:true
in JQuery) then you should be using size() in the success callback of your function, after the content has been added.
$.ajax({
url: requestUrl,
type: 'POST',
dataType: 'json',
data: {},
success: function(response) {
$('#container').html(response.data);
if($('someSearch').size() > 0)
alert('exists');
}
});
You could use something like:
$('#loader').load('url', {variable1:var1}, function () {
if($('#'+mydiv).length != 1) {
// do stuff
}
});
That should look for anything loaded after your load call is finished loading.
I run into the exact same problem with the ticker after page content has been loaded using ajax - my solution was to use the livequery plugin : http://github.com/brandonaaron/livequery/downloads. I then use it in the following way:
$('.ticker').livequery(function() {
if ($(this).length > 0) {
var thisObj = $(this);
if (thisObj.length > 1) {
jQuery.each(thisObj, function() {
systemObject.tickerExe($(this));
});
} else {
systemObject.tickerExe(thisObj);
}
}
});
I hope this helps.
Ensure your div isn't hidden when checking length. Usually, hidden div's can cause lots of problems.
精彩评论