我有以下内容:一组按钮div,每个div都有唯一的信息
<div class="button">
<div id="first">
Johny
</div>
<div id="second">
Dog
</div>
<div id="third">
Pasta
</div>
</div>
<div class="button">
<div id="first">
Bob
</div>
<div id="second">
Cat
</div>
<div id="third">
Noodles
</div>
</div>
.
.
.
我正在尝试这样做,以便当点击其中一个按钮时,我可以检查内部div的值。
例如
$('.button').on('click', function () {
// Check to see if the text of the 'first' div is
// johnny or bob or something else
});
答案 0 :(得分:0)
首先,你不能对页面中的多个元素使用相同的id.So,而是使用class.Ex:
<div class="button">
<div class="first">
Johny
</div>
<div class="second">
Dog
</div>
<div class="third">
Pasta
</div>
</div>
<div class="button">
<div class="first">
Bob
</div>
<div class="second">
Cat
</div>
<div class="third">
Noodles
</div>
</div>
现在在javascript:
$('.button').on('click', function () {
var first=this.getElementsByClassName("first")[0];//gets first element of this button
var second=this.getElementsByClassName("second")[0];
var third=this.getElementsByClassName("third")[0];
//Now you do what ever you want
});
答案 1 :(得分:0)
尝试$(this).children(":first").text()
获取拳头文字
答案 2 :(得分:0)
<script>
$('.button').on('click', function () {
if ($(this).find("#first").html().trim() == "Johny") {
console.log("The first div is Johny");
} else if ($(this).find("#first").html().trim() == "Bob") {
console.log("The first div is Bob");
}
});
</script>
答案 3 :(得分:0)
给每个div自己的点击处理程序怎么样? (你需要使用独特的ID才能正常工作)
<script type="text/javascript">
var bchildren = $('.button').children();
$(bchildren).click(function() {
console.log($(this).html());
});
}
</script>