我正在尝试隐藏子元素不包含具有所需类的 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: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>
第一个标签 <div>
.
关于jquery - 如果子 <span> 不存在,我如何隐藏父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17077798/