[英]How to find a class within a div id using jquery?
When the user click the like button, I am trying to capture the number in the class 'badge'. 当用户单击“赞”按钮时,我正在尝试捕获“徽章”类中的数字。 Here's what I have in my JS so far where I find the div id containing the elements but I'm having trouble going down and finding .badge within this div: 到目前为止,这是我在JS中所拥有的,在其中找到包含元素的div id,但是在向下查找并在此div中查找.badge时遇到了麻烦:
//Like annotation JS
$('.liking').click(function (e){
e.preventDefault();
div = $(this).closest('div').attr('id');
console.log(div);
})
//End of liking annotation JS
<div id = 'div1'>
<% @annotations.each do |annotation| %>
<p><strong>Name</strong>
<p class = 'lead' style = 'font-size: 14px; line-height: 23px;'>
<%= annotation.annotation %>
</p>
<p>
<small>
<span class = 'badge' style = 'font-size: 12px;'>0</span>
<a href = "#" class = 'liking'>
Like
</a>
</small>
</p>
<hr class="featurette-divider" style = 'margin:15px;'>
<% end %> <!-- End of verse annotations -->
</div>
You don't necessarily need the ID, you can use the find
method, you can also use siblings
method. 您不一定需要ID,可以使用find
方法,也可以使用siblings
方法。
$('.liking').click(function (e){
e.preventDefault();
var $badge = $(this).closest('div').find('.badge');
// var $badge = $(this).siblings('.badge');
console.log($badge.text());
})
badge = $(this).closest('div').find('.badge');
但是在您的HTML中, badge
总是在liking
之前就出现了,因此您可以执行以下操作:
badge = $(this).siblings('.badge');
Try this code: 试试这个代码:
var text = $(this).siblings('span.badge').text();
var number = parseInt(text, 10);
Tried this? 试过这个吗?
$('.liking').click(function (e){
e.preventDefault();
div = $(this).closest('div').find('.badge');
console.log(div);
})
here is working link http://jsfiddle.net/ASN7c/ 这是工作链接http://jsfiddle.net/ASN7c/
Will .badge
always be the parent element of the .liking
link? .badge
一直是.liking
链接的父元素吗?
If so, you can simply do: 如果是这样,您可以简单地执行以下操作:
$('.liking').click(function (e){
e.preventDefault();
var $badge = $(this).prev();
console.log($badge.text());
})
Check out http://jsfiddle.net/2c9xz/ 查看http://jsfiddle.net/2c9xz/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.