Reputation: 195
My code is:
<body>
<div id="main"></div>
<button>click me</button>
<script type="text/javascript">
$("<div></div>").load("1.html").appendTo($("#main"));
alert($("li").length);
$("button").click(function() {
alert($("li").length);
});
</script>
</body>
And the 1.html:
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
</ul>
At first it alerts 0;But when i click the button, it alerts 5.Why? And how can I get the number of li when at the first alert window?
Upvotes: 0
Views: 46
Reputation: 47172
This is because .load()
is asynchronous, which means that when the .load()
has fired the script you have continues to execute thus alerting 0
.
But when you click the load is most likely finished and then you'll get the correct length.
To fix this, use the callback that you can provide to load()
which will be executed when the call has finished.
$('<div></div>').load('1.html', function(data) {
alert($("li").length);
});
Upvotes: 3