jquery选择器,用于直接在父div

时间:2015-12-26 20:28:00

标签: jquery html jquery-selectors

我有一个div结构,如下面的代码所示。可能有多个父div具有p0,p1,p2等ID。我试图直接在id为p的div下找到子div。我需要找到与非空子div分开的空子div。

当我运行下面的代码时,方法getEmptyDivs返回0个元素,而方法getNonEmptyDivs返回包含所有子空和非空div的12个元素。

此问题的演示位于以下网址:demo code sample

未返回正确数量的元素的示例代码

<div id='p0'>
     <div>some content</div>
     <div></div>
     <div>some content</div>
     <div></div>
     <div>some content</div>
     <div>some content</div>
    </div>
    <div id='p1'>
     <div>some content</div>
     <div></div>
     <div>some content</div>
     <div></div>
     <div>some content</div>
     <div>some content</div>
</div>
<button type="button" onclick="var x =  getEmptyDivs(); alert(x.length);">Get Empty Divs</button>
<button type="button" onclick="var x =  getNonEmptyDivs(); alert(x.length);">Get Non-Empty Divs</button>
<script>
function getEmptyDivs() { 
   return $("div[id^='p'] > div[innerHTML='']");
}
function getNonEmptyDivs() { 
   return $("div[id^='p'] > div[innerHTML!='']");
}
</script>

我已尝试过上面的代码,但它返回的元素数量不正确。

问题:我可以使用哪个选择器直接在id为p的div下获取所有空div元素的列表,以及获取类似非div的选择器空div?

2 个答案:

答案 0 :(得分:2)

您可以使用:empty:not(:empty)选择器:

function getEmptyDivs() {
    return $("div[id^='p'] > div:empty");
}

function getNonEmptyDivs() {
    return $("div[id^='p'] > div:not(:empty)");
}

Example fiddle

http://api.jquery.com/empty-selector/

http://api.jquery.com/not-selector/

答案 1 :(得分:1)

您可以使用子选择器并过滤掉空白内容:

$("#p0 > div").filter(function () {
  return $(this).is(":empty");
});

<强>段

function getEmptyDivs() { 
  return $("div[id^='p'] > div:empty");
}
function getNonEmptyDivs() { 
  return $("div[id^='p'] > div:not(:empty)");
}
<div id='p0'>
  <div>some content</div>
  <div></div>
  <div>some content</div>
  <div></div>
  <div>some content</div>
  <div>some content</div>
</div>
<div id='p1'>
  <div>some content</div>
  <div></div>
  <div>some content</div>
  <div></div>
  <div>some content</div>
  <div>some content</div>
</div>
<button type="button" onclick="var x =  getEmptyDivs(); alert(x.length);">Get Empty Divs</button>
<button type="button" onclick="var x =  getNonEmptyDivs(); alert(x.length);">Get Non-Empty Divs</button>