Number of Elements, update and present
I have a div within which elements are dynamically added and removed. I'd like to present a number somewhere that keeps track of the new total number of elements within this div.
I was using .length() to find the number of elements, stored in a variable. I'm not sure how to present that variable/value in the html though.
<span> "" + list_Count</span>
The above doesn't work.
I'm also not sure how to get this to update dynamically, i 开发者_JAVA百科figured if the counts were a function, then i could run the function whenever the functions that change things are run.
Update the <span>
element with your value:
<span class="current_count">0</span>
<script type="text/javascript">
function updateCount() {
$("span.current_count").text( $(".container").children().length );
}
</script>
Call the updateCount()
function each time you modify the number of children in your parent element.
$("a.addDiv").click(function(e){
e.preventDefault();
$("<div>").text("New Div").appendTo(".container");
updateCount();
});
Online demo: http://jsbin.com/etivu3/edit
In addition to what Jonathan Sampson said, if you want to get the total number of elements within a tag (ie. child elements), you could use the following:
$('#yourTag').children().length
精彩评论