I’m having a problem trying to detect if a table exists using jQuery. The table has no class or ID.
What I’m trying to achieve is to not have the following code fire unless a table exists:
function tableAltRows()
{
$("#content table tr:even").each(function(){
$(this).addClass("alt");
});
}
$(tableAltRows);
So I changed the last line to:
if ($('table').length > 0) {
$(tableAltRows);
}
But the line checking the table length never returns anything other than 0. As a test, if I change it to == 0 it calls the tableAltRows function. I’m not that familiar with jQuery, so I ass开发者_StackOverflow社区ume I’m missing something obvious?
I suspect that you're not calling your function when the DOM is ready. Try:
$(document).ready(function() {
if($('table').length) {
alert('hello');
}
});
If you are calling the element before it exists, it will not work.
You can:
- Insert the script after the element
- Make the script execute when the page is ready
See this example
精彩评论