[英]Identify which element was clicked, among a set of similar elements, in jquery
I have an HTML page which contains posts. 我有一个包含帖子的HTML页面。
Post is defined by: 帖子定义为:
<div class="post"> <p>...</p> <a href="#" class="post-react">Like</a> <input type="hidden" name="post-id" value="[postid]"> </div>
A single page can contain many such posts. 一个页面可以包含许多此类帖子。 When I click "Like", how do I detect which post element's "Like" button was clicked?
当我单击“喜欢”时,如何检测单击了哪个帖子元素的“喜欢”按钮?
I tried this in jquery: 我在jQuery中尝试了这个:
$(function() { $('.post-react').bind('click', function() { $.getJSON('...', { post_id: $('input[name="post-id"]', this).val() }, function(data) { //something }); return false; }); });
$('input[name="post-id"]', this)
is looking for an input that is a descendant of this
but the input is not inside the <a>
, it is a sibling $('input[name="post-id"]', this)
正在寻找的输入的后裔this
,但是输入不是里面<a>
,它是同级
Use next()
or siblings()
instead or traverse to the post
and use find()
使用
next()
或siblings()
代替或遍历post
并使用find()
post_id: $(this).next().val()
// OR
post_id: $(this).siblings('input[name="post-id"]').val()
// OR
post_id: $(this).closest('.post').find('input[name="post-id"]').val()
Note that bind()
is a very old method that is superseded by on()
请注意,
bind()
是一个非常古老的方法,已由on()
取代
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.