简体   繁体   English

父母的jQuery选择器

[英]jquery selector of parents

I have this html structure: 我有这个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>

in jquery I call a on-click-event for the class "ocond": 在jQuery中,我为类“ ocond”调用了一个单击事件:

now I want to modify the text in class dropbtn (there are around 100 with this name). 现在我想修改dropbtn类中的文本(此名称大约有100个)。 So i tried it with this jquery line: 所以我尝试了这个jQuery行:

  $(this).parents('.dropbtn').text("conditionvalue");

I also tried: 我也尝试过:

$(this).parents('.dropdownedit').siblings('.dropbtn').text("conditionvalue");

but I had no success. 但我没有成功。 anyone can point me to the right selector? 谁能指出我正确的选择器? thanks in advance! 提前致谢!

Use $(this).parent() to navigate from the .ocond to the .dropdown-content , and then you can use .siblings('.dropbtn') to get to the .dropbtn sibling: 使用$(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> 

Your 你的

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

didn't work because .dropbtn is not a parent of the .ocond s, and 无效,因为.dropbtn不是.dropbtn的父.ocond ,并且

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

didn't work because the .dropbtn is not a sibling of the .dropdownedit . 没有工作,因为.dropbtn不是的兄弟.dropdownedit

You should probably only use .parents if you want to select multiple parents of the element in question - otherwise, probably better to use .closest (which will select one ancestor matching the passed selector) or .parent (which will select just the immediate parent element). 如果要选择所涉及元素的多个父级,则应该仅使用.parents否则,最好使用.closest (将选择一个与传递的选择器匹配的祖先)或.parent (仅选择直接父级)元件)。

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

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