Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - 计算带Java的Div中有多少UL元素?(Count how many UL Elements there are in a Div with Javascript?)

I am dynamically adding UL elements to a DIV element.

(我正在将UL元素动态添加到DIV元素。)

I would like to be able to count how many UL elements there are inside the DIV so that once all the ULs are removed dynamically I can delete the DIV that they are contained in.

(我希望能够计算DIV中有多少个UL元素,以便一旦动态删除所有UL,就可以删除其中包含的DIV。)

<div id="000">

<ul id="000-1">
<li>Stuff</li>
<li>Stuff</li>
</ul>

<ul id="000-2">
<li>Stuff</li>
<li>Stuff</li>
</ul>

</div>

Is there a simple Javascript solution that counts the amount of ULs so that I can do something like this.. ?

(是否有一个简单的Javascript解决方案可以计算UL的数量,以便我可以执行类似的操作。)

if(ulcount == 0){

var remove = document.getElementById("000");
remove.innerHTML = '';
results.parentNode.removeChild("000");

}

Thanks.

(谢谢。)

  ask by Wez translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@Cheeso's answer is a good pure-JS solution.

(@Cheeso的答案是一个很好的纯JS解决方案。)

But, if you're using jQuery, the process can be made simpler.

(但是,如果您使用的是jQuery,则可以简化此过程。)

jQuery('div#000').children('ul').length;

The above code will return the number of child ul elements of the div#000 .

(上面的代码将返回div#000的子ul元素的数量。)

To update the count when you add elements dynamically, you will have to create a function and call it to update the number whenever a change occurs:

(要在动态添加元素时更新计数,您将必须创建一个函数并在发生更改时调用它以更新数字:)

function countUls() {jQuery('div#000').children('ul').length;}

Bind that to an event so that it will be called when you want to update the number.

(将该事件绑定到事件,以便在您要更新号码时将其调用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...