Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于内部没有类的jQuery选择器_Javascript_Jquery_Jquery Selectors - Fatal编程技术网

Javascript 基于内部没有类的jQuery选择器

Javascript 基于内部没有类的jQuery选择器,javascript,jquery,jquery-selectors,Javascript,Jquery,Jquery Selectors,我需要根据不在元素内的内容选择元素 <div class="person"> <div class="name">Jason</div> </div> <div class="person"> </div> 杰森 使用person类选择第二个div需要做什么。我知道有具有和不属性,我是否需要以某种方式将它们组合起来以使其正常工作?您可以将其用作选择器: $(".person:not(:has(.name))")

我需要根据不在元素内的内容选择元素

<div class="person">
  <div class="name">Jason</div>
</div>

<div class="person">
</div>

杰森

使用
person
类选择第二个
div
需要做什么。我知道有
具有
属性,我是否需要以某种方式将它们组合起来以使其正常工作?

您可以将其用作选择器:

$(".person:not(:has(.name))")
但我建议您对其进行过滤:

因为:has()是jQuery扩展,而不是CSS的一部分 规范中,使用:has()的查询无法利用 本机DOM querySelectorAll()提供的性能提升 方法


最简单的jquery解决方案
$('.person:empty')
,但第二个div必须没有空格

<div class="person">
  <div class="name">Jason</div>
</div>

<div class="person"></div>

杰森

你可以做这样的事情

function getPersonWithNoNameField() {
  $('.person').each(function() {
    if($(this).find('div.name').length === 0) {
      var ele = $(this);
      console.log(ele.html());
      return ele;
    }
  });
}

getPersonWithNoNameField();

For your need, you can customise the function to return element which you want.

我不会太担心
:has
的低效性。我猜jQuery在内部做的事情很像
.filter()
解决方案,所以这两个解决方案很可能非常相似。@Roamer-1888 Ya这基本上就是在做的事情
:has()
,但是这个伪选择器有一些错误,但是在jq>1.8.2.哎哟,这意味着从v1.1.4到v1.8.1这段时间里,jQuery选择器肯定有问题。还有一个事实是jQuery选择器经常与CSS选择器混淆——这个问题被错误地命名和标记,我现在已经解决了,但是一些反对票可能来自这种误解。
function getPersonWithNoNameField() {
  $('.person').each(function() {
    if($(this).find('div.name').length === 0) {
      var ele = $(this);
      console.log(ele.html());
      return ele;
    }
  });
}

getPersonWithNoNameField();

For your need, you can customise the function to return element which you want.