Py学习  »  Jquery

jquery父选择器

hillcode • 7 年前 • 1972 次点击  

我有这个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");

但我没有成功。谁能给我指出正确的选择器?提前谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43460
文章 [ 1 ]  |  最新文章 7 年前
CertainPerformance
Reply   •   1 楼
CertainPerformance    7 年前

使用 $(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')

不工作是因为 Delptn 不是 奥康德 S和

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

因为 Delptn 不是 .dropdownedit .

你应该只使用 .parents 如果你想选择 倍数 有关元素的父元素-否则,最好使用 .closest (将选择 一 与传递的选择器匹配的祖先)或 .parent (只选择直接父元素)。