[英]Find child of parent container using jquery
I am probably looking at this the wrong way, but I am having trouble locating an element within my page and am hoping someone can help. 我可能以错误的方式看待此问题,但是我在页面中定位元素时遇到困难,希望有人可以提供帮助。
The scenario is this: I have a <ul>
containing a number of <li>'s
which in turn contain <a href>'s
. 场景是这样的:我有一个
<ul>
其中包含许多<li>'s
而这些<li>'s
又包含<a href>'s
。 I am getting the value of the rel attribute of the clicked <a href>
and want to replace the text in a <span class='someclass'>
which is located in a parent container. 我正在获取单击的
<a href>
的rel属性的值,并想替换位于父容器中的<span class='someclass'>
的文本。 There may be more than one of these <span class='someclass'>
on the page so I need to find the closest one. 页面上可能有一个以上的
<span class='someclass'>
,所以我需要找到最接近的一个。
Here is how my HTML looks 这是我的HTML外观
<h3 class="my-header-class">
<span class="some-class">Title Text</span>
</h3>
<ul class="tabs">
<li><a rel="Title Text 1" href="#tab1">Link 1</a></li>
<li><a rel="Title Text 2" href="#tab2">Link 2</a></li>
<li><a rel="Title Text 3" href="#tab3">Link 3</a></li>
</ul>
Here is my javascript 这是我的javascript
var titletext = $(this).attr('rel');
var container = $(this).parent().children(".some-class");
container.text(titletext);
The titletext variable is being set with the correct text but I am unable to replace the text of the <span class='someclass'>
. 用正确的文本设置了titletext变量,但是我无法替换
<span class='someclass'>
的文本。 I assume because I am not finding it correctly. 我认为是因为找不到正确的位置。
Thanks, Tristan 谢谢特里斯坦
$(this).parent().parent().prev().children(".some-class");
<h3> <!-- PREV OF UL -->
<span> <!-- CHILDREN OF H3 -->
<ul> <!-- PARENT OF <LI> AND <A> -->
<li> <!-- PARENT OF <A> AND CHILDREN OF <UL> -->
<a> <!-- CHILDREN OF <UL> AND <LI> -->
$(this).parent().parent().prev('h3').children(".some-class")
$("ul.tabs a").click(function() {
var titletext = $(this).attr('rel');
$(this).closest("ul.tabs").prev().find(".some-class").text(titletext);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.