开发者

Number of Elements, update and present

开发者 https://www.devze.com 2023-03-11 13:32 出处:网络
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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消