How to count with jquery number of elements on remote page?
I would like to count number of elements on remote page: For开发者_JAVA百科 example remote page:
test.html with following structure
<div id="Layout">
<div class="product">...</div>
<div class="product">...</div>
<div class="product">...</div>
</div>
Then I would like call from test2.html
<script type="text/javascript">
$(document).ready(function(){
$('#result').load('/test.html #Layout product').length();
});
</script>
This code is not working. What is the right way to do it? Thank you.
You need to wait until the elements are actually loaded, you can use the callback function argument of the $.load
method:
$(document).ready(function(){
$('#result').load('/test.html #Layout', function () {
var products = $('.product', this).length;
alert(products);
});
});
Check the above example here.
Also, if you don't want to insert the loaded elements into the DOM, you can load them into a new empty element, for example:
$('<div></div>').load('/test.html #Layout', function () {
var products = $('.product', this).length;
alert(products);
});
精彩评论