【问题标题】:How to Access First Child Div of the Parent Div [duplicate]如何访问父 Div 的第一个子 Div [重复]
【发布时间】:2015-01-18 12:23:30
【问题描述】:
在一个 div 的点击事件中,我试图为一个变量分配该 div 父 div 的第一个子元素的文本值。例如,html 是这样的:
<div class="parentDiv">
<div class="firstChild">
1234
</div>
<div class="secondChild">
Hello
</div>
<div class="thridChild">
Bye
</div>
</div>
所以我希望它在单击父 div 内的任何内容时为变量分配 firstChild div 的文本值。你会怎么做呢?
【问题讨论】:
标签:
javascript
jquery
html
backbone.js
【解决方案1】:
您不想使用第二个选择器,因为这会降低性能。
相反,使用.find()在您当前的元素中搜索
var text = 'new text';
$('.parentDiv').on('click', function() {
$(this).find('div:first').html(text);
});
【解决方案2】:
.parentDiv:first-child 或
.parentDiv:first 或
.parentDiv:nth-child(1) 甚至
.firstChild:first-of-type
【解决方案3】:
$(function(){
$('.parentDiv div').click(function(){
var $parent = $(this).closest('.parentDiv');
//Do whatever you want with $parent
});
});
使用 jQuery tree traversal 查找父级(.closest 位)
【解决方案4】:
你可以使用:
var text = $('.parentDiv:nth-child(1)').html();
【解决方案5】:
您可以使用子> 和:first 选择器的组合。像这样:
var divValue = $(".parentDiv>div:first").text();
这将选择第一个子 div 元素并检索它的文本值。
Here is a working example
当然,如果你有一个课程,你可以使用$(".firstChild").text();,但我认为这只是为了帮助解释这个问题。