我有这个 html 结构:
<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content" style="display: none;">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div></div>
在 jquery 中,我为“ocond”类调用了一个点击事件:
现在我想修改 dropbtn 类中的文本(这个名字大约有 100 个)。所以我用这个 jquery 线试了一下:
$(this).parents('.dropbtn').text("conditionvalue");
我也试过:
$(this).parents('.dropdownedit').siblings('.dropbtn').text("conditionvalue");
但我没有成功。任何人都可以指向我正确的选择器?提前致谢!
用于$(this).parent()
从 导航.ocond
到.dropdown-content
,然后您可以使用.siblings('.dropbtn')
到达.dropbtn
同级:
$('.ocond').on('click', function() {
$(this).parent().siblings('.dropbtn').text("conditionvalue");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div>
</div>
你的
$(this).parents('.dropbtn')
没有工作,因为.dropbtn
它不是.ocond
s的父级,并且
$(this).parents('.dropdownedit').siblings('.dropbtn')
没有工作,因为.dropbtn
不是 的兄弟姐妹.dropdownedit
。
.parents
如果您想选择相关元素的多个父元素,您可能只应该使用- 否则,可能更好地使用.closest
(它将选择一个与传递的选择器匹配的祖先)或.parent
(它将只选择直接的父元素)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句