从一篇文章中得到第一个孩子ID,只有一个类名,用Jquery
问题描述:
我有我这样的代码。它应该显示为带有日期的水平按钮。当用户点击其中一个按钮时,该框会展开,显示其中的图片。从一篇文章中得到第一个孩子ID,只有一个类名,用Jquery
我想获得用jquery点击的文章的第一个孩子ID,以便能够显示带有第一个孩子ID的gallery_items,而在末尾没有“_title”。但我没有定义。
我的HTML:
<section id="gallery">
<article class="gallery_date">
<div id="1389848400_title">16-01-2014</div>
<div class="gallery_items" id="1389848400">
<a href="content/uploads/261689_10150238069156283_4353481_n.jpg">261689_10150238069156283_4353481_n.jpg</a><br>
<a href="content/uploads/IMG_4667.jpg">IMG_4667.jpg</a><br>
<a href="content/uploads/millenium2.png">millenium2.png</a><br>
</div>
</article>
<article class="gallery_date">
<div id="1389762000_title">15-01-2014</div>
<div class="gallery_items" id="1389762000">
<a href="content/uploads/IMG_4661.jpg">IMG_4661.jpg</a><br>
</div>
</article>
<article class="gallery_date">
<div id="1389675600_title">14-01-2014</div>
<div class="gallery_items" id="1389675600">
<a href="content/uploads/bcn.png">bcn.png</a><br>
<a href="content/uploads/logoenmedio.png">logoenmedio.png</a><br>
</div>
</article>
</section>
我的Jquery:
$().ready(function() {
$(".gallery_date").click(function(event) {
console.log($(".gallery_date:first-child").attr("id"));
});
});
感谢
答
“我试图获得用jquery点击的文章的第一个孩子ID,以便能够显示
gallery_items
的第一个孩子ID,而最后没有"_title"
。”
这样做:
$(this).children().first().prop("id").split("_")[0];
或者没有jQuery的,所以它不是那么详细:
this.children[0].id.split("_")[0];
但是,如果这是对ID唯一需要的话你可以选择与.children()
同类的元素:
$(this).children(".gallery_items")
答
试试这个:
$(document).ready(function() {
$(".gallery_date").click(function(event) {
console.log($(this).find('.gallery_items:first-child').attr("id"));
});
});
答
没有 “_title”的第一个孩子ID。
您可以使用.replace()
删除'_title'
,或者您可以使用.split()
$(document).ready(function() {
$(".gallery_date").click(function(event) {
var id = $(this).children().first().attr("id")
console.log(id.replace('_title',''));
console.log(id.split("_")[0]);
});
});
答
$(".gallery_date").click(function(event) {
console.log($(this).children().first().attr("id"));
});
答
如果你的HTML的结构事情是这样的,你也可以只使用的.next()方法来获得gallery_items格,像这样的,所以你不必担心会标识和再检索DOM元素:
$(document).ready(function() {
$(".gallery_date").click(function() {
$(this).next(".gallery_items").slideDown();
});
});
'$(本).find( “:第一胎”)。ATTR(“ID “).split('_')。shift()'并使用' $(document).ready(function(){...});' –