简体   繁体   English

jQuery选择同一父级中具有特定类的另一个元素

[英]jQuery select another element with certain class in same parent

let say i have this div假设我有这个 div

<div id='parent'>
  <button id='button'></button>
  <div id='child'>
     <div id='grandchild' class='lookAtMe'>
          Some JSON text
     </div>
  </div>
</div>

I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)我想给 #button 一个点击事件,它返回 #lookAtMe div 的文本,特定于它共享父/祖父的 div(在这种情况下,#parent div)

I tried using:我尝试使用:

 $("#button").on("click",function(){
     var ReturnedText = $(this).parent(".lookAtMe").text();
     console.log(RetrunedText);
 });

But the console log would retruned (empty string).但是控制台日志会返回(空字符串)。

Where did i do wrong?我哪里做错了? please help.请帮忙。 Thankyou very much.非常感谢。

Because there is no parent with that class.因为那个班级没有父母。 You need find() .你需要find()

Actually you need to write其实你需要写

 var ReturnedText = $(this).parent().find(".lookAtMe").text();

 $("#button").on("click",function(){ var ReturnedText = $(this).parent().find(".lookAtMe").text(); console.log(ReturnedText); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <button id='button'></button> <div id='child'> <div id='grandchild' class='lookAtMe'> Some JSON text </div> </div> </div>

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

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