Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.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
Jquery 如果子元素<;span>;不存在_Jquery_Html_Css - Fatal编程技术网

Jquery 如果子元素<;span>;不存在

Jquery 如果子元素<;span>;不存在,jquery,html,css,Jquery,Html,Css,我试图隐藏任何父元素,这些父元素的子元素不包含带有必需类的span标记。例如: <html> <body> <div class="optionfield" id="fieldAdTitle"> <label class="optionLabel" for="Title"> <span class="required">*</span> Title <label clas

我试图隐藏任何父元素,这些父元素的子元素不包含带有必需类的span标记。例如:

<html>
<body>
<div class="optionfield" id="fieldAdTitle">
      <label class="optionLabel" for="Title">
      <span class="required">*</span>
      Title
      <label class="optionLabel" for="Title">
   <input type="text" class="" value="" name="Title" id="Title">
</div>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
   <input type="text" class="" value="" name="Title" id="Title">
</div>
<div class="optionfield" id="fieldAdTitle">
   <label class="optionLabel" for="Title">
      Title
   </label>
   <input type="text" class="" value="" name="Title" id="Title">
</div>
</body>
</html>

*
标题
标题
标题
您可以这样做

$('.optionfield').each(function(){
    if($(this).find('span.required').length == 0){
        $(this).hide();
    }
});

证据就在这里;)

一行,但可能不如其他答案有效:

$('.optionfield:not(:has(span.required))').hide();
在行动中:

$('.optionfield:not(:has(span.required))).hide()

  • * 标题
  • 标题 标题
    您可以尝试以下方法:

        $('.optionfield') //Get your sources
        .filter(function(){ //APply filter
              return $(this).find('span.required').length == 0}) // to get the elements with no span.required as child
        .hide(); //hide the filtered out ones.
    

    我个人建议:

    // hide them all:
    $('.optionfield').hide()
    // find the descendant elements:
    .find('span.required')
    // having found them, find the closest ancestor:
    .closest('.optionfield')
    // show them:
    .show().
    
    参考资料:


    好的。我正式印象深刻的是,我能够在发布后几分钟内得到答案。非常感谢卡蒂克!那是我打字的错误。谢谢你的回复@约瑟夫加西亚,如果你问我这是一条路,应该被接受。jQuery方法
    :has
    :not
    正是为此而发明的
    $('.optionfield
    已返回所有元素的集合,因此无需创建额外的
    。each()
    函数并在其中执行操作。