2

我正在尝试隐藏任何子元素不包含所需类的跨度标记的父元素。例如:

<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>
4

4 回答 4

5

单线,但可能不如其他答案有效:

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

在行动:

$('.optionfield:not(:has(span.required))').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="optionfield" id="fieldAdTitle">
      <label class="optionLabel" for="Title">
      <span class="required">*</span>
      Title
    </label>
    <input type="text" class="" value="" name="Title" id="Title" />

</li>
<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>

此外,那里还有一些格式不正确的 HTML:<label>在 first 中有两个未闭合的标签<div>

于 2013-06-13T01:15:23.243 回答
4

你可以做

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

证明在小提琴中;)

于 2013-06-13T01:11:23.843 回答
2

你可以试试这个:

    $('.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.

演示

见过滤器()

于 2013-06-13T01:18:36.830 回答
1

我个人建议:

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

参考:

于 2013-06-13T01:21:49.853 回答