繁体   English   中英

父母的jQuery选择器

[英]jquery selector of parents

我有这个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不是.dropbtn的父.ocond ,并且

$(this).parents('.dropdownedit').siblings('.dropbtn')

没有工作,因为.dropbtn不是的兄弟.dropdownedit

如果要选择所涉及元素的多个父级,则应该仅使用.parents否则,最好使用.closest (将选择一个与传递的选择器匹配的祖先)或.parent (仅选择直接父级)元件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM