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>最初の に 2 つの閉じられていないタグがあります<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.

デモ

filter()を参照

于 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 に答える