HTML:
<div class="col-xs-3">
<div class="row firstset">
<h3 class="redtext">CLICK RED</h3>
<div class="col-xs-6 guess green"></div>
<div class="col-xs-6 guess red"></div>
<div class="col-xs-6 guess blue"></div>
<div class="col-xs-6 guess yellow"></div>
</div><!--end of row-->
</div><!--end of col-->
<div class="col-xs-3">
<div class="row secondset">
<h3 class="greentext">CLICK GREEN</h3>
<div class="col-xs-6 guess orange"></div>
<div class="col-xs-6 guess purple"></div>
<div class="col-xs-6 guess blue"></div>
<div class="col-xs-6 guess green"></div>
</div><!--end of row-->
</div><!--end of col-->
所以我总共有八个。这是JS。
JS:
$guess = $(".guess");
$guess.on('click', function() {
alert($(this).siblings().find("h3").html());
});
当点击带有类猜测的div时,我想要定位div是兄弟姐妹的标题的内部内容,但是这个方法给了我undefined。我甚至尝试过html(),但它不起作用。我该怎么做呢?
答案 0 :(得分:2)
删除搜索后代元素的.find()
。你只需要检查兄弟姐妹:
$guess.on('click', function() {
alert($(this).siblings("h3").html());
});
<强> jsFiddle example 强>
答案 1 :(得分:0)
$('.guess').click(function(){
console.log("using siblings "+$(this).siblings('h3').text());//no find needed
console.log("using parent "+$(this).parent().find('h3').text());
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3">
<div class="row firstset">
<h3 class="redtext">CLICK RED</h3>
<div class="col-xs-6 guess green">1</div>
<div class="col-xs-6 guess red">1</div>
<div class="col-xs-6 guess blue">1</div>
<div class="col-xs-6 guess yellow">1</div>
</div><!--end of row-->
</div><!--end of col-->
<div class="col-xs-3">
<div class="row secondset">
<h3 class="greentext">CLICK GREEN</h3>
<div class="col-xs-6 guess orange">1</div>
<div class="col-xs-6 guess purple">1</div>
<div class="col-xs-6 guess blue">1</div>
<div class="col-xs-6 guess green">1</div>
</div><!--end of row-->
</div>
&#13;
答案 2 :(得分:0)
只需删除.find()
,因为它用于获取当前匹配元素集中每个元素的后代,由选择器,jQuery对象或元素过滤。