2011-11-23 119 views
0

我有一些htmls,其中一些标签没有任何孩子,我想识别它们并计算这些标签的数量。没有孩子选择

我曾尝试以下,它似乎并没有工作:

var count = 0; 
$("th[class=gridlabel]").each(function(){ 
if($("th[class=gridlabel]").children().length<1) 
{ 
count++; 
} 
}); 
return count; 
alert(count); 

不知道什么是这里的问题。


我已经加入从HTML源代码一些额外的脚本,我要确保“计数”只算前两个标签,对于“回答3”和“答案4”,因为他们的标签做不可以有孩子:

<tr> 
    <th class="gridlabel">answer 3</th> 
    <td headers="q12_header1" class="gridcell"><input><div><span>answer 3</span><label>1</label></div></td> 
    <td headers="q12_header2" class="gridcell"><input><div><label></label></div></td> 
    </tr> 
    <tr> 
    <th class="gridlabel">answer 4</th> 
    <td headers="q12_header1" class="gridcell"><input><div><span>answer 4</span><label>1</label></div></td> 
    <td headers="q12_header2" class="gridcell"><input><div><label></label></div></td> 
    </tr> 
    <tr> 
    <th class="gridlabel">other specify 1<input><label>other specify 1</label></th> 
    <td><input><div><span>other specify 1</span><label>1</label></div></td> 
    <td><input><div><label>2</label></div></td> 
    </tr> 

回答

3
var count = $("th.gridlabel:empty").length; 
return count; 

更新

给你提供,你可以使用这样的事情,如果你知道“非空”细胞将有一个输入孩子的HTML:

var count = $('th:not(:has(input))').length; 

如果你想要的东西多一点灵活,但稍长一点,你可以做一些事情:

var count = 0; 
$('th').each(function(){ 
    if($(this).children().length < 1) 
    { 
     count++; 
    } 
}) 

这样你就可以覆盖任何可能的子标签。这真的取决于你需要什么。

+0

感谢Leo,它似乎也不工作,下面是html的一部分: – user1041029

+0

我认为你的html复制/粘贴在这里不起作用。你应该自己编辑问题。 – Leo

+0

刚加入,谢谢 – user1041029

0

试试这个:

var count = 0; 
$("th[class=gridlabel]").each(function(){ 
    if(this.children().length<1) 
    { 
     count++; 
    } 
}); 
return count; 
alert(count);